/
new-template-part.js
81 lines (73 loc) · 1.83 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* External dependencies
*/
import { kebabCase } from 'lodash';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { useDispatch } from '@wordpress/data';
import { Button } from '@wordpress/components';
import { addQueryArgs } from '@wordpress/url';
import apiFetch from '@wordpress/api-fetch';
import { __ } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
/**
* Internal dependencies
*/
import CreateTemplatePartModal from '../create-template-part-modal';
export default function NewTemplatePart( { postType } ) {
const [ isModalOpen, setIsModalOpen ] = useState( false );
const { createErrorNotice } = useDispatch( noticesStore );
async function createTemplatePart( { title, area } ) {
if ( ! title ) {
createErrorNotice( __( 'Title is not defined.' ), {
type: 'snackbar',
} );
return;
}
try {
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.href = addQueryArgs( window.location.href, {
postId: templatePart.id,
postType: 'wp_template_part',
} );
} catch ( error ) {
const errorMessage =
error.message && error.code !== 'unknown_error'
? error.message
: __(
'An error occurred while creating the template part.'
);
createErrorNotice( errorMessage, { type: 'snackbar' } );
}
}
return (
<>
<Button
variant="primary"
onClick={ () => {
setIsModalOpen( true );
} }
>
{ postType.labels.add_new }
</Button>
{ isModalOpen && (
<CreateTemplatePartModal
closeModal={ () => setIsModalOpen( false ) }
onCreate={ createTemplatePart }
/>
) }
</>
);
}