import { capitalCase } from 'change-case'; import { store as coreDataStore } from '@wordpress/core-data'; import type { Updatable, WpTemplatePart } from '@wordpress/core-data'; import type { Block, BlockConfiguration } from '@wordpress/blocks'; import { select } from '@wordpress/data'; import { symbolFilled } from '@wordpress/icons'; import { addFilter } from '@wordpress/hooks'; import { decodeEntities } from '@wordpress/html-entities'; import initBlock from '../utils/init-block'; import type { BlockModule } from '../utils/types'; import metadata from './block.json'; import edit from './edit'; import { enhanceTemplatePartVariations } from './variations'; import type { TemplatePartAttributes } from './types'; const { name } = metadata; export { metadata, name }; export const settings: BlockModule< TemplatePartAttributes >[ 'settings' ] = { icon: symbolFilled, __experimentalLabel: ( { slug, theme }: TemplatePartAttributes ) => { // Attempt to find entity title if block is a template part. // Require slug to request, otherwise entity is uncreated and will throw 404. if ( ! slug ) { return; } const { getCurrentTheme, getEditedEntityRecord } = select( coreDataStore ); const entity = getEditedEntityRecord( 'postType', 'wp_template_part', ( theme || getCurrentTheme()?.stylesheet ) + '//' + slug ) as Updatable< WpTemplatePart > | false; if ( ! entity ) { return; } return ( decodeEntities( entity.title ) || capitalCase( entity.slug || '' ) ); }, edit, }; export const init = () => { addFilter( 'blocks.registerBlockType', 'core/template-part', enhanceTemplatePartVariations ); // Prevent adding template parts inside post content. // Note: this code previously restricted 'core/post-template', which is why the filter // is called `removeTemplatePartsFromPostTemplates`. The filter name is unchanged // for backwards compatibility. See https://github.com/WordPress/gutenberg/pull/86377. const DISALLOWED_PARENTS = [ 'core/post-content' ]; addFilter( 'blockEditor.__unstableCanInsertBlockType', 'core/block-library/removeTemplatePartsFromPostTemplates', ( canInsert: boolean, blockType: BlockConfiguration, rootClientId: string, { getBlock, getBlockParentsByBlockName, }: { getBlock: ( clientId: string ) => Block | null; getBlockParentsByBlockName: ( clientId: string, blockName: string | string[] ) => string[]; } ) => { if ( blockType.name !== 'core/template-part' ) { return canInsert; } for ( const disallowedParentType of DISALLOWED_PARENTS ) { const hasDisallowedParent = getBlock( rootClientId )?.name === disallowedParentType || getBlockParentsByBlockName( rootClientId, disallowedParentType ).length; if ( hasDisallowedParent ) { return false; } } return canInsert; } ); return initBlock( { name, metadata: metadata as BlockModule< TemplatePartAttributes >[ 'metadata' ], settings, } ); };