import { useEffect, useId, useState } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { useUi } from '../runtime'; import { apiPost, apiPut } from '../api/client'; import { errorText } from '../lib/format'; const BLANK = { name: '', description: '', visibility: 'internal' }; /** * New tag and Edit tag, one small dialog: the name, an optional description * and whether signup forms may offer it. A tag is a group in code * (`/groups`); a public one can be picked on signup forms and on each * subscriber's preferences page, an internal one is the owner's alone. * * @param {Object} props * @param {boolean} props.open Whether it shows. * @param {?Object} props.tag The tag edited, or null for a new one. * @param {Function} props.onClose Called to close it. * @param {Function} props.onSaved Called with the saved tag. * @return {Element} The dialog. */ export default function TagDialog( { open, tag = null, onClose, onSaved } ) { const { ui } = useUi(); const { Button, Dialog, Field, HelpTip, Input, Switch, Textarea, toast } = ui; const switchId = useId(); const [ draft, setDraft ] = useState( BLANK ); const [ saving, setSaving ] = useState( false ); const isNew = ! tag?.id; // Each opening starts from the tag as it is now. useEffect( () => { if ( open ) { setDraft( { name: tag?.name || '', description: tag?.description || '', visibility: tag?.visibility === 'public' ? 'public' : 'internal', } ); } }, [ open, tag ] ); const save = async () => { const name = draft.name.trim(); if ( ! name || saving ) { return; } const data = { name, description: draft.description.trim(), visibility: draft.visibility, }; setSaving( true ); try { const saved = isNew ? await apiPost( 'groups', data ) : await apiPut( `groups/${ tag.id }`, data ); onSaved( saved || { ...tag, ...data } ); } catch ( err ) { toast.error( errorText( err, isNew ? __( 'Could not create the tag.', 'mailpuff' ) : __( 'Could not change the tag.', 'mailpuff' ) ) ); } finally { setSaving( false ); } }; return ( ! next && onClose() } title={ isNew ? __( 'New tag', 'mailpuff' ) : __( 'Edit tag', 'mailpuff' ) } size="sm" footer={ <> } >
{ ( a11y ) => ( setDraft( { ...draft, name: e.target.value } ) } onKeyDown={ ( e ) => e.key === 'Enter' && save() } /> ) } { ( a11y ) => (