/** * Settings › Privacy, Your data: export everything Mailpuff holds as one * JSON file, and import such a file on another site. Two rows, each a label, * a `?` and its button; deleting everything is the row after them * (./DangerBlock.jsx). */ import { useRef, useState } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { useUi } from '../../runtime'; import { apiGet, apiPost } from '../../api/client'; import { errorText } from '../../lib/format'; /** * A row that acts at once: its name and `?` on the left, its button on the * right. Rows sit in a `ToggleList`, which draws the hairlines. * * @param {Object} props * @param {*} props.label What the row does. * @param {*} props.tip Optional help. * @param {*} props.children The button. * @return {Element} The row. */ export function ActionRow( { label, tip, children } ) { const { ui } = useUi(); return (
{ label } { tip && { tip } }
{ children }
); } /** * @return {Element} The export and import rows. */ export default function DataBlock() { const { ui } = useUi(); const { Button, toast } = ui; const file = useRef( null ); const [ exporting, setExporting ] = useState( false ); const [ importing, setImporting ] = useState( false ); // No `include`: the export holds campaigns, subscribers, lists and settings. const exportAll = async () => { setExporting( true ); try { const data = await apiGet( 'export' ); const url = URL.createObjectURL( new Blob( [ JSON.stringify( data, null, 2 ) ], { type: 'application/json', } ) ); const a = document.createElement( 'a' ); a.href = url; a.download = `mailpuff-export-${ new Date() .toISOString() .slice( 0, 10 ) }.json`; a.click(); URL.revokeObjectURL( url ); } catch ( err ) { toast.error( errorText( err, __( 'Export failed.', 'mailpuff' ) ) ); } setExporting( false ); }; // The file is the export as it was downloaded, `{ version, site, data }`; // the server imports its `data`. const importFile = async ( e ) => { const picked = e.target.files?.[ 0 ]; e.target.value = ''; if ( ! picked ) { return; } setImporting( true ); try { const data = JSON.parse( await picked.text() ); const result = await apiPost( 'import', { ...data, mode: 'merge', } ); toast.success( sprintf( /* translators: 1: campaigns imported, 2: subscribers imported. */ __( 'Imported %1$s campaigns and %2$s subscribers.', 'mailpuff' ), result?.imported?.campaigns || 0, result?.imported?.contacts || 0 ) ); } catch ( err ) { toast.error( errorText( err, __( 'Import failed. Check the file.', 'mailpuff' ) ) ); } setImporting( false ); }; return ( <> ); }