-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathuse-patterns-state.js
63 lines (58 loc) · 1.63 KB
/
use-patterns-state.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
/**
* External dependencies
*/
import { map } from 'lodash';
/**
* WordPress dependencies
*/
import { useCallback } from '@wordpress/element';
import { cloneBlock } from '@wordpress/blocks';
import { useDispatch, useSelect } from '@wordpress/data';
import { __, sprintf } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../../store';
/**
* Retrieves the block patterns inserter state.
*
* @param {Function} onInsert function called when inserter a list of blocks.
* @param {string=} rootClientId Insertion's root client ID.
*
* @return {Array} Returns the patterns state. (patterns, categories, onSelect handler)
*/
const usePatternsState = ( onInsert, rootClientId ) => {
const { patternCategories, patterns } = useSelect(
( select ) => {
const { __experimentalGetAllowedPatterns, getSettings } = select(
blockEditorStore
);
return {
patterns: __experimentalGetAllowedPatterns( rootClientId ),
patternCategories: getSettings()
.__experimentalBlockPatternCategories,
};
},
[ rootClientId ]
);
const { createSuccessNotice } = useDispatch( noticesStore );
const onClickPattern = useCallback( ( pattern, blocks ) => {
onInsert(
map( blocks, ( block ) => cloneBlock( block ) ),
pattern.name
);
createSuccessNotice(
sprintf(
/* translators: %s: block pattern title. */
__( 'Block pattern "%s" inserted.' ),
pattern.title
),
{
type: 'snackbar',
}
);
}, [] );
return [ patterns, patternCategories, onClickPattern ];
};
export default usePatternsState;