edit.js (3942B)
1 /** 2 * Internal dependencies 3 */ 4 import importReusableBlock from '../utils/import'; 5 import insertImportedBlocks from '../utils/insert'; 6 7 /** 8 * WordPress dependencies 9 */ 10 const { __ } = wp.i18n; 11 const { withInstanceId } = wp.compose; 12 const { Fragment, Component } = wp.element; 13 const { MediaUploadCheck } = wp.blockEditor; 14 const { DropZone, FormFileUpload, Placeholder, Notice } = wp.components; 15 16 const ALLOWED_BG_MEDIA_TYPES = [ 'json' ]; 17 18 /** 19 * Block edit function 20 */ 21 class Edit extends Component { 22 constructor() { 23 super( ...arguments ); 24 25 this.state = { 26 isLoading: false, 27 error: null, 28 }; 29 30 this.isStillMounted = true; 31 this.addFile = this.addFile.bind( this ); 32 } 33 34 componentDidMount() { 35 const { file } = this.props.attributes; 36 37 if ( file ) { 38 this.setState( { isLoading: true } ); 39 this.addFile( file ); 40 } 41 } 42 43 componentWillUnmount() { 44 this.isStillMounted = false; 45 } 46 47 addFile( files ) { 48 let file = files[ 0 ]; 49 50 if ( files.target ) { 51 file = event.target.files[ 0 ]; 52 } 53 54 if ( ! file ) { 55 return; 56 } 57 this.setState( { isLoading: true } ); 58 59 importReusableBlock( file ) 60 .then( ( reusableBlock ) => { 61 if ( ! this.isStillMounted ) { 62 return; 63 } 64 65 this.setState( { isLoading: false } ); 66 insertImportedBlocks( this.props.clientId, reusableBlock, this.props.onClose ); 67 } ) 68 .catch( ( error ) => { 69 if ( ! this.isStillMounted ) { 70 return; 71 } 72 73 let uiMessage; 74 switch ( error.message ) { 75 case 'Invalid JSON file': 76 uiMessage = __( 'Invalid JSON file', redux_templates.i18n ); 77 break; 78 case 'Invalid Reusable Block JSON file': 79 uiMessage = __( 'Invalid Reusable Block JSON file', redux_templates.i18n ); 80 break; 81 default: 82 uiMessage = __( 'Unknown error', redux_templates.i18n ); 83 } 84 85 this.setState( { isLoading: false, error: uiMessage } ); 86 } ); 87 } 88 89 render() { 90 const { isLoading, error } = this.state; 91 92 return ( 93 <Placeholder 94 icon="download" 95 label={ __( 'Import a Template from JSON - Redux', redux_templates.i18n ) } 96 instructions={ __( 'Drag a file or upload a new one from your device.', redux_templates.i18n ) } 97 className="editor-media-placeholder" 98 notices={ error && ( 99 <Notice status="error"> 100 { error } 101 </Notice> 102 ) } 103 > 104 <Fragment> 105 <MediaUploadCheck> 106 <DropZone 107 onFilesDrop={ this.addFile } 108 label={ __( 'Import from JSON', redux_templates.i18n ) } 109 /> 110 <FormFileUpload 111 isLarge 112 className="editor-media-placeholder__button button button-primary" 113 onChange={ this.addFile } 114 accept={ ALLOWED_BG_MEDIA_TYPES } 115 isBusy={ isLoading } 116 disabled={ isLoading } 117 multiple={ false } 118 > 119 { __( 'Upload', redux_templates.i18n ) } 120 </FormFileUpload> 121 </MediaUploadCheck> 122 </Fragment> 123 </Placeholder> 124 ); 125 } 126 } 127 128 export default withInstanceId( Edit );