-
Notifications
You must be signed in to change notification settings - Fork 4k
/
convert-to-template-part.js
79 lines (74 loc) · 1.85 KB
/
convert-to-template-part.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* External dependencies
*/
import { kebabCase } from 'lodash';
/**
* WordPress dependencies
*/
import { useDispatch } from '@wordpress/data';
import {
BlockSettingsMenuControls,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { MenuItem } from '@wordpress/components';
import { createBlock, serialize } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
import { store as coreStore } from '@wordpress/core-data';
import { store as noticesStore } from '@wordpress/notices';
/**
* Internal dependencies
*/
import CreateTemplatePartModal from '../create-template-part-modal';
export default function ConvertToTemplatePart( { clientIds, blocks } ) {
const [ isModalOpen, setIsModalOpen ] = useState( false );
const { replaceBlocks } = useDispatch( blockEditorStore );
const { saveEntityRecord } = useDispatch( coreStore );
const { createSuccessNotice } = useDispatch( noticesStore );
const onConvert = async ( { title, area } ) => {
const templatePart = await saveEntityRecord(
'postType',
'wp_template_part',
{
slug: kebabCase( title ),
title,
content: serialize( blocks ),
area,
}
);
replaceBlocks(
clientIds,
createBlock( 'core/template-part', {
slug: templatePart.slug,
theme: templatePart.theme,
} )
);
createSuccessNotice( __( 'Template part created.' ), {
type: 'snackbar',
} );
};
return (
<>
<BlockSettingsMenuControls>
{ ( { onClose } ) => (
<MenuItem
onClick={ () => {
setIsModalOpen( true );
onClose();
} }
>
{ __( 'Make template part' ) }
</MenuItem>
) }
</BlockSettingsMenuControls>
{ isModalOpen && (
<CreateTemplatePartModal
closeModal={ () => {
setIsModalOpen( false );
} }
onCreate={ onConvert }
/>
) }
</>
);
}