/**
* Feedback the screens call without rendering anything themselves: toasts
* and the confirm dialog. KitProvider mounts the one toaster and the one
* confirm dialog; `toast` and `useConfirm` then work from anywhere under it.
*/
import {
createContext,
useCallback,
useContext,
useMemo,
useRef,
useState,
} from 'react';
import { Toaster, toast } from 'sonner';
import { __ } from '@wordpress/i18n';
import { Button, Dialog } from './components';
import { TooltipProvider } from './ui/tooltip';
export { toast };
const ConfirmContext = createContext( null );
/**
* The confirm dialog and its promise. `confirm( { title, description,
* confirmLabel, cancelLabel, danger } )` resolves true when the person
* confirms and false on cancel, Escape or a click outside. A danger confirm
* opens with Cancel focused, so a second Enter cannot do the damage.
*
* @param {Object} props Component props.
* @param {Node} props.children The app.
* @return {Element} The provider.
*/
function ConfirmProvider( { children } ) {
const [ state, setState ] = useState( null );
const resolver = useRef( null );
const confirm = useCallback( ( opts = {} ) => {
return new Promise( ( resolve ) => {
// A second call settles the first as "no".
if ( resolver.current ) {
resolver.current( false );
}
resolver.current = resolve;
setState( {
title: opts.title || __( 'Are you sure?', 'mailpuff' ),
description: opts.description,
confirmLabel:
opts.confirmLabel ||
( opts.danger
? __( 'Delete', 'mailpuff' )
: __( 'Confirm', 'mailpuff' ) ),
cancelLabel: opts.cancelLabel || __( 'Cancel', 'mailpuff' ),
danger: Boolean( opts.danger ),
} );
} );
}, [] );
const settle = ( result ) => {
if ( resolver.current ) {
resolver.current( result );
}
resolver.current = null;
setState( null );
};
const value = useMemo( () => confirm, [ confirm ] );
return (
{ children }
);
}
/**
* @return {Function} confirm( options ): Promise.
*/
export function useConfirm() {
const confirm = useContext( ConfirmContext );
if ( ! confirm ) {
throw new Error( 'useConfirm requires near the root.' );
}
return confirm;
}
/**
* Wraps the app with what the kit's floating parts need: tooltips, the
* confirm dialog and the toaster. Mount it once, inside `#mailpuff-root`.
*
* @param {Object} props Component props.
* @param {Node} props.children The app.
* @return {Element} The provider.
*/
export function KitProvider( { children } ) {
return (
{ children }
);
}