index.js
103 lines
| 1 | /** |
| 2 | * External dependencies |
| 3 | */ |
| 4 | import { isUndefined } from 'lodash'; |
| 5 | |
| 6 | /** |
| 7 | * WordPress dependencies |
| 8 | */ |
| 9 | const { __ } = wp.i18n; |
| 10 | const { withSelect } = wp.data; |
| 11 | const { SelectControl, Button, Placeholder, Spinner } = wp.components; |
| 12 | |
| 13 | /** |
| 14 | * Internal dependencies |
| 15 | */ |
| 16 | import { getSiteUrl } from '../../utils'; |
| 17 | import GiveBlankSlate from '../blank-slate'; |
| 18 | import NoForms from '../no-form'; |
| 19 | |
| 20 | /** |
| 21 | * Render form select UI |
| 22 | */ |
| 23 | const giveFormOptionsDefault = { value: '0', label: __( '-- Select Form --' ) }; |
| 24 | |
| 25 | const SelectForm = ( { forms, attributes, setAttributes } ) => { |
| 26 | //Attributes |
| 27 | const { prevId } = attributes; |
| 28 | |
| 29 | // Event(s) |
| 30 | const getFormOptions = () => { |
| 31 | // Add API Data To Select Options |
| 32 | |
| 33 | let formOptions = []; |
| 34 | |
| 35 | if ( ! isUndefined( forms ) ) { |
| 36 | formOptions = forms.map( |
| 37 | ( { id, title: { rendered: title } } ) => { |
| 38 | return { |
| 39 | value: id, |
| 40 | label: title === '' ? `${ id } : ${ __( 'No form title' ) }` : title, |
| 41 | }; |
| 42 | } |
| 43 | ); |
| 44 | } |
| 45 | // Add Default option |
| 46 | formOptions.unshift( giveFormOptionsDefault ); |
| 47 | |
| 48 | return formOptions; |
| 49 | }; |
| 50 | |
| 51 | const setFormIdTo = id => { |
| 52 | setAttributes( { id: Number( id ) } ); |
| 53 | }; |
| 54 | |
| 55 | const resetFormIdTo = () => { |
| 56 | setAttributes( { id: Number( prevId ) } ); |
| 57 | setAttributes( { prevId: undefined } ); |
| 58 | }; |
| 59 | |
| 60 | // Render Component UI |
| 61 | let componentUI; |
| 62 | |
| 63 | if ( ! forms ) { |
| 64 | componentUI = <Placeholder><Spinner/></Placeholder>; |
| 65 | } else if ( forms && forms.length === 0 ) { |
| 66 | componentUI = <NoForms />; |
| 67 | } else { |
| 68 | componentUI = ( |
| 69 | <GiveBlankSlate title={ __( 'Give Donation form' ) }> |
| 70 | <SelectControl |
| 71 | className="give-blank-slate__select" |
| 72 | options={ getFormOptions() } |
| 73 | onChange={ setFormIdTo } |
| 74 | /> |
| 75 | |
| 76 | <Button isPrimary |
| 77 | isLarge href={ `${ getSiteUrl() }/wp-admin/post-new.php?post_type=give_forms` }> |
| 78 | { __( 'Add New Form' ) } |
| 79 | </Button> |
| 80 | |
| 81 | { |
| 82 | prevId && |
| 83 | <Button isLarge |
| 84 | onClick={ resetFormIdTo }> |
| 85 | { __( 'Cancel' ) } |
| 86 | </Button> |
| 87 | } |
| 88 | </GiveBlankSlate> |
| 89 | ); |
| 90 | } |
| 91 | |
| 92 | return componentUI; |
| 93 | }; |
| 94 | |
| 95 | /** |
| 96 | * Export with forms data |
| 97 | */ |
| 98 | export default withSelect( ( select ) => { |
| 99 | return { |
| 100 | forms: select( 'core' ).getEntityRecords( 'postType', 'give_forms' ), |
| 101 | }; |
| 102 | } )( SelectForm ); |
| 103 |