-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathinsert-into-block.ts
More file actions
69 lines (63 loc) · 1.88 KB
/
insert-into-block.ts
File metadata and controls
69 lines (63 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* WordPress dependencies
*/
import { createBlock } from '@wordpress/blocks';
import { select, dispatch } from '@wordpress/data';
import { store as blockEditorStore } from '@wordpress/block-editor';
/**
* Internal dependencies
*/
import type { UploadedImage } from '../types';
/**
* Inserts an uploaded image into the target block by updating its attributes.
*
* For `core/gallery`, a new inner `core/image` block is appended. For all
* other supported blocks the relevant attributes are set directly.
*
* @param {string} blockName The name of the target block.
* @param {string} clientId The client ID of the target block.
* @param {Function} setAttributes The block's setAttributes callback.
* @param {UploadedImage} uploadedImage The image returned by uploadImage.
*/
export function insertIntoBlock(
blockName: string,
clientId: string,
setAttributes: ( attrs: Record< string, unknown > ) => void,
uploadedImage: UploadedImage
): void {
const { id, url, title: alt } = uploadedImage;
switch ( blockName ) {
case 'core/image':
setAttributes( { id, url, alt } );
break;
case 'core/cover':
setAttributes( {
id,
url,
alt,
dimRatio: 50,
isDark: false,
sizeSlug: 'full',
} );
break;
case 'core/media-text':
setAttributes( { mediaId: id, mediaUrl: url, mediaType: 'image' } );
break;
case 'core/gallery': {
const { getBlocks } = select( blockEditorStore );
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const replaceInnerBlocks = ( dispatch( blockEditorStore ) as any )
?.replaceInnerBlocks as
| ( ( clientId: string, blocks: unknown[] ) => void )
| undefined;
if ( replaceInnerBlocks ) {
const existing = getBlocks( clientId );
replaceInnerBlocks( clientId, [
...existing,
createBlock( 'core/image', { id, url, alt } ),
] );
}
break;
}
}
}