| 1 |
/** |
| 2 |
* Check if the block can be loaded in the current template. |
| 3 |
* |
| 4 |
* @since 4.2.8.4 |
| 5 |
* @version 1.0.0 |
| 6 |
*/ |
| 7 |
import { unregisterBlockType, getBlockType } from '@wordpress/blocks'; |
| 8 |
import { subscribe, select } from '@wordpress/data'; |
| 9 |
|
| 10 |
let currentPostIdOld = null; |
| 11 |
const checkTemplatesCanLoadBlock = ( templates, metadata, callBack ) => { |
| 12 |
subscribe( () => { |
| 13 |
const metaDataNew = { ...metadata }; |
| 14 |
const store = select( 'core/editor' ) || null; |
| 15 |
|
| 16 |
if ( ! store || typeof store.getCurrentPostId !== 'function' || ! store.getCurrentPostId() ) { |
| 17 |
return; |
| 18 |
} |
| 19 |
|
| 20 |
const currentPostId = store.getCurrentPostId(); |
| 21 |
|
| 22 |
if ( currentPostId === null ) { |
| 23 |
return; |
| 24 |
} |
| 25 |
|
| 26 |
if ( currentPostIdOld === currentPostId ) { |
| 27 |
return; |
| 28 |
} |
| 29 |
|
| 30 |
currentPostIdOld = currentPostId; |
| 31 |
if ( getBlockType( metaDataNew.name ) ) { |
| 32 |
unregisterBlockType( metaDataNew.name ); |
| 33 |
|
| 34 |
if ( templates.includes( currentPostId ) ) { |
| 35 |
metaDataNew.ancestor = null; |
| 36 |
callBack( metaDataNew ); |
| 37 |
} else { |
| 38 |
if ( ! metaDataNew.ancestor ) { |
| 39 |
metaDataNew.ancestor = []; |
| 40 |
} |
| 41 |
callBack( metaDataNew ); |
| 42 |
} |
| 43 |
} |
| 44 |
} ); |
| 45 |
}; |
| 46 |
|
| 47 |
export { checkTemplatesCanLoadBlock }; |
| 48 |
|