-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
79 lines (72 loc) · 1.94 KB
/
index.js
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
70
71
72
73
74
75
76
77
78
79
/**
* External dependencies
*/
import { map } from 'lodash';
/**
* WordPress dependencies
*/
import { useMemo, useCallback } from '@wordpress/element';
import { parse, cloneBlock } from '@wordpress/blocks';
import { useSelect, useDispatch } from '@wordpress/data';
import { ENTER, SPACE } from '@wordpress/keycodes';
import { __, sprintf } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import BlockPreview from '../block-preview';
function BlockPattern( { pattern, onClick } ) {
const { title, content } = pattern;
const blocks = useMemo( () => parse( content ), [ content ] );
return (
<div
className="block-editor-patterns__item"
role="button"
onClick={ () => onClick( pattern, blocks ) }
onKeyDown={ ( event ) => {
if ( ENTER === event.keyCode || SPACE === event.keyCode ) {
onClick( blocks );
}
} }
tabIndex={ 0 }
>
<div className="block-editor-patterns__item-preview">
<BlockPreview blocks={ blocks } autoHeight />
</div>
<div className="block-editor-patterns__item-title">{ title }</div>
</div>
);
}
function BlockPatterns( { patterns } ) {
const getBlockInsertionPoint = useSelect( ( select ) => {
return select( 'core/block-editor' ).getBlockInsertionPoint;
} );
const { insertBlocks } = useDispatch( 'core/block-editor' );
const { createSuccessNotice } = useDispatch( 'core/notices' );
const onClickPattern = useCallback( ( pattern, blocks ) => {
const { index, rootClientId } = getBlockInsertionPoint();
insertBlocks(
map( blocks, ( block ) => cloneBlock( block ) ),
index,
rootClientId,
false
);
createSuccessNotice(
sprintf( __( 'Pattern "%s" inserted' ), pattern.title ),
{
type: 'snackbar',
}
);
}, [] );
return (
<div className="block-editor-patterns">
{ patterns.map( ( pattern, index ) => (
<BlockPattern
key={ index }
pattern={ pattern }
onClick={ onClickPattern }
/>
) ) }
</div>
);
}
export default BlockPatterns;