-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathuse-fallback-value-clearer.js
61 lines (52 loc) · 1.85 KB
/
use-fallback-value-clearer.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
import { useLayoutEffect } from '@wordpress/element';
import { useEntityProp } from '@wordpress/core-data';
import { store as blockEditorStore } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { FALLBACK_VALUE_PLACEHOLDER, POST_TYPE } from '../constants';
/**
* This allows the user to edit values that are bound to an attribute.
* There is a bug in the Bindings API preventing this from working,
* so here's our workaround.
*
* TODO Remove when Gutenberg 19.2 gets released.
*
* See https://github.com/Automattic/create-content-model/issues/63 for the problem.
*/
export const useFallbackValueClearer = () => {
const [ meta, setMeta ] = useEntityProp( 'postType', POST_TYPE, 'meta' );
const blockToMetaMap = useSelect( ( select ) => {
const blocks = select( blockEditorStore ).getBlocks();
const map = {};
const processBlock = ( block ) => {
const bindings = block.attributes?.metadata?.bindings || {};
Object.entries( bindings ).forEach( ( [ , binding ] ) => {
if ( binding.source === 'core/post-meta' ) {
if ( ! map[ block.clientId ] ) {
map[ block.clientId ] = [];
}
map[ block.clientId ].push( {
metaKey: binding.args.key,
blockName: block.attributes.metadata.name,
} );
}
} );
// Process inner blocks if they exist, like core/button is inside core/buttons.
if ( block.innerBlocks && block.innerBlocks.length > 0 ) {
block.innerBlocks.forEach( processBlock );
}
};
blocks.forEach( processBlock );
return map;
}, [] );
useLayoutEffect( () => {
Object.entries( blockToMetaMap ).forEach( ( [ , metaInfos ] ) => {
metaInfos.forEach( ( { metaKey } ) => {
const value = meta[ metaKey ];
if ( value === FALLBACK_VALUE_PLACEHOLDER ) {
setMeta( { [ metaKey ]: '' } );
}
} );
} );
}, [ meta, setMeta, blockToMetaMap ] );
return null;
};