-
Notifications
You must be signed in to change notification settings - Fork 4k
/
new-template-part.js
99 lines (87 loc) · 2.21 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* External dependencies
*/
import { kebabCase } from 'lodash';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
import { store as coreStore } from '@wordpress/core-data';
/**
* Internal dependencies
*/
import { useHistory } from '../routes';
import CreateTemplatePartModal from '../create-template-part-modal';
export default function NewTemplatePart( { postType } ) {
const history = useHistory();
const [ isModalOpen, setIsModalOpen ] = useState( false );
const { createErrorNotice } = useDispatch( noticesStore );
const { saveEntityRecord } = useDispatch( coreStore );
const { getLastEntitySaveError } = useSelect( coreStore );
async function createTemplatePart( { title, area } ) {
if ( ! title ) {
createErrorNotice( __( 'Title is not defined.' ), {
type: 'snackbar',
} );
return;
}
try {
const templatePart = await saveEntityRecord(
'postType',
'wp_template_part',
{
slug: kebabCase( title ),
title,
content: '',
area,
}
);
const lastEntitySaveError = getLastEntitySaveError(
'postType',
'wp_template_part',
templatePart.id
);
if ( lastEntitySaveError ) {
throw lastEntitySaveError;
}
setIsModalOpen( false );
// Navigate to the created template part editor.
history.push( {
postId: templatePart.id,
postType: templatePart.type,
} );
// TODO: Add a success notice?
} catch ( error ) {
const errorMessage =
error.message && error.code !== 'unknown_error'
? error.message
: __(
'An error occurred while creating the template part.'
);
createErrorNotice( errorMessage, { type: 'snackbar' } );
setIsModalOpen( false );
}
}
return (
<>
<Button
variant="primary"
onClick={ () => {
setIsModalOpen( true );
} }
>
{ postType.labels.add_new }
</Button>
{ isModalOpen && (
<CreateTemplatePartModal
closeModal={ () => setIsModalOpen( false ) }
onCreate={ createTemplatePart }
/>
) }
</>
);
}