/
new-template-part.js
67 lines (59 loc) · 1.38 KB
/
new-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
/**
* External dependencies
*/
import { kebabCase } from 'lodash';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { Button } from '@wordpress/components';
import { addQueryArgs } from '@wordpress/url';
import apiFetch from '@wordpress/api-fetch';
/**
* Internal dependencies
*/
import CreateTemplatePartModal from '../create-template-part-modal';
export default function NewTemplatePart( { postType } ) {
const [ isModalOpen, setIsModalOpen ] = useState( false );
async function createTemplatePart( { title, area } ) {
if ( ! title ) {
return;
}
const templatePart = await apiFetch( {
path: '/wp/v2/template-parts',
method: 'POST',
data: {
slug: kebabCase( title ),
title,
content: '',
area,
},
} );
// Navigate to the created template part editor.
window.location.search = addQueryArgs( '', {
page: 'gutenberg-edit-site',
postId: templatePart.id,
postType: 'wp_template_part',
} );
// Wait for async navigation to happen before closing the modal.
await new Promise( () => {} );
}
return (
<>
<Button
variant="primary"
onClick={ () => {
setIsModalOpen( true );
} }
>
{ postType.labels.add_new }
</Button>
{ isModalOpen && (
<CreateTemplatePartModal
closeModal={ () => setIsModalOpen( false ) }
onCreate={ createTemplatePart }
/>
) }
</>
);
}