-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
index.js
100 lines (92 loc) · 2.38 KB
/
index.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
100
/**
* WordPress dependencies
*/
import {
Button,
Modal,
__experimentalHStack as HStack,
__experimentalVStack as VStack,
TextControl,
} from '@wordpress/components';
import { __, sprintf } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';
import { useState } from '@wordpress/element';
import { store as coreStore } from '@wordpress/core-data';
import { store as noticesStore } from '@wordpress/notices';
export default function AddNewPageModal( { onSave, onClose } ) {
const [ isCreatingPage, setIsCreatingPage ] = useState( false );
const [ title, setTitle ] = useState( '' );
const { saveEntityRecord } = useDispatch( coreStore );
const { createErrorNotice, createSuccessNotice } =
useDispatch( noticesStore );
async function createPage( event ) {
event.preventDefault();
if ( isCreatingPage ) {
return;
}
setIsCreatingPage( true );
try {
const newPage = await saveEntityRecord(
'postType',
'page',
{
status: 'draft',
title,
slug: title || __( 'No title' ),
},
{ throwOnError: true }
);
onSave( newPage );
createSuccessNotice(
sprintf(
// translators: %s: Title of the created template e.g: "Category".
__( '"%s" successfully created.' ),
newPage.title?.rendered || title
),
{
type: 'snackbar',
}
);
} catch ( error ) {
const errorMessage =
error.message && error.code !== 'unknown_error'
? error.message
: __( 'An error occurred while creating the page.' );
createErrorNotice( errorMessage, {
type: 'snackbar',
} );
} finally {
setIsCreatingPage( false );
}
}
return (
<Modal title={ __( 'Draft a new page' ) } onRequestClose={ onClose }>
<form onSubmit={ createPage }>
<VStack spacing={ 3 }>
<TextControl
/* eslint-disable jsx-a11y/no-autofocus */
autoFocus
/* eslint-enable jsx-a11y/no-autofocus */
label={ __( 'Page title' ) }
onChange={ setTitle }
placeholder={ __( 'No title' ) }
value={ title }
/>
<HStack spacing={ 2 } justify="end">
<Button variant="tertiary" onClick={ onClose }>
{ __( 'Cancel' ) }
</Button>
<Button
variant="primary"
type="submit"
isBusy={ isCreatingPage }
aria-disabled={ isCreatingPage }
>
{ __( 'Create draft' ) }
</Button>
</HStack>
</VStack>
</form>
</Modal>
);
}