/**
* JavaScript code for AJAX requests with Notices functionality on admin screens.
*
* @package TablePress
* @subpackage Views JavaScript
* @author Tobias Bäthge
* @since 3.1.0
*/
/**
* WordPress dependencies.
*/
import {
Icon,
} from '@wordpress/components';
import { RawHTML } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { buildQueryString } from '@wordpress/url';
/**
* Internal dependencies.
*/
import { TablePressIconSimple } from '../../img/tablepress-icon';
/**
* Default callback for handling specifics of a successful request.
*
* @param {Object} data
*/
const onSuccessfulRequestDefault = ( data ) => {
const actionMessages = {
success_save: __( 'The changes were saved successfully.', 'tablepress' ),
};
const notice = {
status: ( data.message.includes( 'error' ) ) ? 'error' : 'success',
content: actionMessages[ data.message ],
type: ( data.message.includes( 'error' ) ) ? 'notice' : 'snackbar',
};
return { notice };
};
/**
* Processes an AJAX request with Notices functionality.
*
* @param {Object} props Function parameters.
* @param {Object} props.requestData Request data.
* @param {Function} props.onSuccessfulRequest Callback for handling a successful save.
* @param {Function} props.setBusyState Callback for setting the busy state.
* @param {Function} props.noticeOperations Callbacks for working with notices.
* @param {Function} props.noticesStoreDispatch Dispatch function for notices store. (Optional, only for "success" Snackbar notices.)
*/
const processAjaxRequest = ( { requestData, onSuccessfulRequest = onSuccessfulRequestDefault, setBusyState, noticeOperations, noticesStoreDispatch } ) => {
/**
* Shows a notice to the user.
*
* @param {Object} notice Notice data.
* @param {string} notice.status Status of the notice (error, success, warning, info).
* @param {string} notice.content Content of the notice.
*/
const showNotice = ( { status, content } ) => {
const id = `notice-${ Date.now() }`;
content = <>
{ /* Notices don't have a DOM ID, so add a custom span which has one, for the fade-out and removal. */ }
${ __( 'These errors were encountered:', 'tablepress' ) }
${ data.error_details }` : '';
throw new Error( `${ __( 'There was a problem with the request.', 'tablepress' ) }
${ debugHtml }` ); } handleRequestSuccess( data ); } ) // Handle errors. .catch( ( error ) => { handleRequestError( error.message ); } ) // Clean up. .finally( () => { // Reset the screen from "is busy" mode. setBusyState( false ); document.body.classList.remove( 'wait' ); } ); /** * Handles a successful AJAX request. * * @param {Object} data Request response data. */ const handleRequestSuccess = ( data ) => { const { notice } = onSuccessfulRequest( data ); if ( notice ) { if ( 'snackbar' === notice.type && 'undefined' !== typeof noticesStoreDispatch ) { // Dispatch a Snackbar notice. noticesStoreDispatch.createSuccessNotice( notice.content, { type: 'snackbar', icon: