import { DropZone, Dialog, Checkbox } from '@elementor/app-ui'; import { Context as TemplatesContext, TemplatesProvider } from '../context/templates'; import BackButton from '../molecules/back-button'; import { useConfirmAction as useConfirmActionBase } from '@elementor/hooks'; // The hook `useConfirmAction` comes from the core plugin, so it is possible that it is not available. const useConfirmActionFallback = ( { action } ) => ( { runAction: action, dialog: { isOpen: false }, } ); const useConfirmAction = useConfirmActionBase ?? useConfirmActionFallback; export default function Import() { const { importTemplates, action, resetActionState } = React.useContext( TemplatesContext ), [ importedTemplate, setImportedTemplate ] = React.useState( null ), isImport = action.current === TemplatesProvider.actions.IMPORT, isUploading = isImport && action.loading, hasError = isImport && action.error; const upload = React.useCallback( ( file ) => { if ( isUploading ) { return; } readFile( file ) .then( ( fileData ) => importTemplates( { fileName: file.name, fileData } ) ) .then( ( response ) => { // For now it show a dialog for the first template ONLY! setImportedTemplate( response.data[ 0 ] ); } ); }, [] ); const { runAction: uploadFile, dialog, checkbox, } = useConfirmAction( { doNotShowAgainKey: 'upload_json_warning_generic_message', action: upload, } ); return (
{ importedTemplate && setImportedTemplate( null ) } /> } { hasError && } { dialog.isOpen && }
); } function readFile( file ) { return new Promise( ( ( resolve ) => { const fileReader = new FileReader(); fileReader.readAsDataURL( file ); fileReader.onload = ( event ) => { // Replace the mime type that prepended to the base64 with empty string and return a // resolved promise only with the base64 string. resolve( event.target.result.replace( /^[^,]+,/, '' ) ); }; } ) ); }