import { useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { useQuery } from '@tanstack/react-query'; import { useUi } from '../runtime'; import { apiGet } from '../api/client'; import { useCreateContact } from '../hooks/use-contacts'; import { errorText, isEmail } from '../lib/format'; /** * Add one contact by hand, optionally straight into groups. * * @param {Object} root0 The props. * @param {boolean} root0.open Whether the dialog is open. * @param {Function} root0.onClose Called to close it. */ export default function AddContactDialog( { open, onClose } ) { const { ui } = useUi(); const { Button, Checkbox, Dialog, Field, Input, toast } = ui; const create = useCreateContact(); const [ email, setEmail ] = useState( '' ); const [ first, setFirst ] = useState( '' ); const [ last, setLast ] = useState( '' ); const [ picked, setPicked ] = useState( [] ); const { data: groupsData } = useQuery( { queryKey: [ 'groups' ], queryFn: () => apiGet( 'groups' ), enabled: !! open, } ); const groups = groupsData?.items || []; const toggleGroup = ( id ) => setPicked( ( now ) => now.includes( id ) ? now.filter( ( g ) => g !== id ) : [ ...now, id ] ); const close = () => { setEmail( '' ); setFirst( '' ); setLast( '' ); setPicked( [] ); onClose(); }; const save = () => { if ( ! isEmail( email ) ) { return; } const data = { email: email.trim(), first_name: first, last_name: last, }; if ( picked.length ) { data.group_ids = picked; } create.mutate( data, { onSuccess: () => { toast.success( __( 'Subscriber added.', 'mailpuff' ) ); close(); }, onError: ( err ) => toast.error( errorText( err, __( 'Could not add the subscriber.', 'mailpuff' ) ) ), } ); }; return ( ! next && close() } title={ __( 'Add subscriber', 'mailpuff' ) } size="sm" footer={ <> } >
{ ( a11y ) => ( setEmail( e.target.value ) } onKeyDown={ ( e ) => e.key === 'Enter' && save() } /> ) }
{ ( a11y ) => ( setFirst( e.target.value ) } /> ) } { ( a11y ) => ( setLast( e.target.value ) } /> ) }
{ groups.length > 0 && ( { () => (
{ groups.map( ( g ) => ( toggleGroup( Number( g.id ) ) } /> ) ) }
) }
) }
); }