-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
use-block-context.js
47 lines (42 loc) · 1.01 KB
/
use-block-context.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
/**
* WordPress dependencies
*/
import { store as blocksStore } from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../../store';
/**
* Returns a context object for a given block.
*
* @param {string} clientId The block client ID.
*
* @return {Record<string,*>} Context value.
*/
export default function useBlockContext( clientId ) {
return useSelect(
( select ) => {
const block = select( blockEditorStore ).getBlock( clientId );
if ( ! block ) {
return undefined;
}
const blockType = select( blocksStore ).getBlockType( block.name );
if ( ! blockType ) {
return undefined;
}
if ( Object.keys( blockType.providesContext ).length === 0 ) {
return undefined;
}
return Object.fromEntries(
Object.entries( blockType.providesContext ).map(
( [ contextName, attributeName ] ) => [
contextName,
block.attributes[ attributeName ],
]
)
);
},
[ clientId ]
);
}