-
Notifications
You must be signed in to change notification settings - Fork 4k
/
use-block-types-state.js
64 lines (57 loc) · 1.61 KB
/
use-block-types-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
64
/**
* WordPress dependencies
*/
import {
createBlock,
createBlocksFromInnerBlocksTemplate,
store as blocksStore,
parse,
} from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';
import { useCallback } from '@wordpress/element';
/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../../store';
/**
* Retrieves the block types inserter state.
*
* @param {string=} rootClientId Insertion's root client ID.
* @param {Function} onInsert function called when inserter a list of blocks.
* @return {Array} Returns the block types state. (block types, categories, collections, onSelect handler)
*/
const useBlockTypesState = ( rootClientId, onInsert ) => {
const { categories, collections, items } = useSelect(
( select ) => {
const { getInserterItems } = select( blockEditorStore );
const { getCategories, getCollections } = select( blocksStore );
return {
categories: getCategories(),
collections: getCollections(),
items: getInserterItems( rootClientId ),
};
},
[ rootClientId ]
);
const onSelectItem = useCallback(
(
{ name, initialAttributes, innerBlocks, syncStatus, content },
shouldFocusBlock
) => {
const insertedBlock =
syncStatus === 'unsynced'
? parse( content, {
__unstableSkipMigrationLogs: true,
} )
: createBlock(
name,
initialAttributes,
createBlocksFromInnerBlocksTemplate( innerBlocks )
);
onInsert( insertedBlock, undefined, shouldFocusBlock );
},
[ onInsert ]
);
return [ items, categories, collections, onSelectItem ];
};
export default useBlockTypesState;