-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathinsert-block.ts
47 lines (42 loc) · 1 KB
/
insert-block.ts
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
/**
* Internal dependencies
*/
import type { Editor } from './index';
interface BlockRepresentation {
name: string;
attributes?: Object;
innerBlocks?: BlockRepresentation[];
}
/**
* Insert a block.
*
* @param this
* @param blockRepresentation Inserted block representation.
*/
async function insertBlock(
this: Editor,
blockRepresentation: BlockRepresentation
) {
await this.page.waitForFunction(
() => window?.wp?.blocks && window?.wp?.data
);
await this.page.evaluate( ( _blockRepresentation ) => {
function recursiveCreateBlock( {
name,
attributes = {},
innerBlocks = [],
}: BlockRepresentation ): Object {
return window.wp.blocks.createBlock(
name,
attributes,
innerBlocks.map( ( innerBlock ) =>
recursiveCreateBlock( innerBlock )
)
);
}
const block = recursiveCreateBlock( _blockRepresentation );
window.wp.data.dispatch( 'core/block-editor' ).insertBlock( block );
}, blockRepresentation );
}
export type { BlockRepresentation };
export { insertBlock };