| 1 |
/** |
| 2 |
* JavaScript code for the "Alert" component. |
| 3 |
* |
| 4 |
* @package TablePress |
| 5 |
* @subpackage Views JavaScript |
| 6 |
* @author Tobias Bäthge |
| 7 |
* @since 3.1.0 |
| 8 |
*/ |
| 9 |
|
| 10 |
/** |
| 11 |
* WordPress dependencies. |
| 12 |
*/ |
| 13 |
import { useCallback, useRef } from 'react'; |
| 14 |
import { |
| 15 |
Button, |
| 16 |
__experimentalHStack as HStack, // eslint-disable-line @wordpress/no-unsafe-wp-apis |
| 17 |
Icon, |
| 18 |
Modal, |
| 19 |
__experimentalVStack as VStack, // eslint-disable-line @wordpress/no-unsafe-wp-apis |
| 20 |
} from '@wordpress/components'; |
| 21 |
import { __ } from '@wordpress/i18n'; |
| 22 |
|
| 23 |
/** |
| 24 |
* Internal dependencies. |
| 25 |
*/ |
| 26 |
import { TablePressIcon } from '../../img/tablepress-icon'; |
| 27 |
|
| 28 |
/** |
| 29 |
* Returns the Alert component's JSX markup. |
| 30 |
* |
| 31 |
* @param {Object} props Component props. |
| 32 |
* @param {Object} props.icon Icon of the alert. Defaults to the TablePress icon. |
| 33 |
* @param {string} props.title Title of the alert. No header will be shown if this is not set. |
| 34 |
* @param {string} props.text Text of the alert. |
| 35 |
* @param {Function} props.onConfirm Callback to confirm the alert. |
| 36 |
* @param {Object} props.modalProps Additional props for the Modal. |
| 37 |
* @return {Object} Alert component. |
| 38 |
*/ |
| 39 |
const Alert = ( { icon = TablePressIcon, title, text, onConfirm, modalProps } ) => { |
| 40 |
const confirmButtonRef = useRef(); |
| 41 |
|
| 42 |
const handleEnter = useCallback( |
| 43 |
( event ) => { |
| 44 |
// Avoid triggering the action when a button is focused, as this can cause a double submission. |
| 45 |
const isConfirmButton = event.target === confirmButtonRef.current; |
| 46 |
|
| 47 |
if ( ! isConfirmButton && 'Enter' === event.key ) { |
| 48 |
onConfirm(); |
| 49 |
event.preventDefault(); // This prevents that the triggering button is "clicked" (via "Enter") again. |
| 50 |
} |
| 51 |
}, |
| 52 |
[ onConfirm ], |
| 53 |
); |
| 54 |
|
| 55 |
return ( |
| 56 |
<Modal |
| 57 |
icon={ <Icon icon={ icon } size={ TablePressIcon === icon ? '36' : '24' } style={ { display: 'flex', marginRight: '1rem' } } /> } |
| 58 |
title={ title } |
| 59 |
__experimentalHideHeader={ undefined === title } |
| 60 |
isDismissible={ false } |
| 61 |
shouldCloseOnEsc={ false } |
| 62 |
shouldCloseOnClickOutside={ false } |
| 63 |
onKeyDown={ handleEnter } |
| 64 |
{ ...modalProps } |
| 65 |
> |
| 66 |
<VStack spacing={ 8 }> |
| 67 |
<span> |
| 68 |
{ text } |
| 69 |
</span> |
| 70 |
<HStack alignment="right"> |
| 71 |
<Button |
| 72 |
ref={ confirmButtonRef } |
| 73 |
variant="primary" |
| 74 |
text={ __( 'OK', 'tablepress' ) } |
| 75 |
onClick={ onConfirm } |
| 76 |
/> |
| 77 |
</HStack> |
| 78 |
</VStack> |
| 79 |
</Modal> |
| 80 |
); |
| 81 |
}; |
| 82 |
|
| 83 |
export { Alert }; |
| 84 |
|