-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathadd-menu-form.js
84 lines (70 loc) · 1.9 KB
/
add-menu-form.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
/**
* External dependencies
*/
import { some } from 'lodash';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { useDispatch } from '@wordpress/data';
import { TextControl, Button } from '@wordpress/components';
import { __, sprintf } from '@wordpress/i18n';
const menuNameMatches = ( menuName ) => ( menu ) =>
menu.name.toLowerCase() === menuName.toLowerCase();
export default function AddMenuForm( { menus, onCreate } ) {
const [ menuName, setMenuName ] = useState( '' );
const { createErrorNotice, createInfoNotice } = useDispatch(
'core/notices'
);
const [ isCreatingMenu, setIsCreatingMenu ] = useState( false );
const { saveMenu } = useDispatch( 'core' );
const createMenu = async ( event ) => {
event.preventDefault();
if ( ! menuName.length ) {
return;
}
if ( some( menus, menuNameMatches( menuName ) ) ) {
const message = sprintf(
// translators: %s: the name of a menu.
__(
'The menu name %s conflicts with another menu name. Please try another.'
),
menuName
);
createErrorNotice( message, { id: 'edit-navigation-error' } );
return;
}
setIsCreatingMenu( true );
const menu = await saveMenu( { name: menuName } );
if ( menu ) {
createInfoNotice( __( 'Menu created' ), {
type: 'snackbar',
isDismissible: true,
} );
onCreate( menu.id );
}
setIsCreatingMenu( false );
};
return (
<form onSubmit={ createMenu }>
<TextControl
// Disable reason: The name field should receive focus when
// component mounts.
// eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus
label={ __( 'Menu name' ) }
value={ menuName }
onChange={ setMenuName }
/>
<Button
className="edit-navigation-header__create-menu-button"
type="submit"
isPrimary
disabled={ ! menuName.length }
isBusy={ isCreatingMenu }
>
{ __( 'Create menu' ) }
</Button>
</form>
);
}