Back

0% Statements 0/13
0% Branches 0/16
0% Functions 0/3
0% Lines 0/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                                                                                                                                 
/* eslint-disable jsdoc/require-jsdoc */
 
import { useQuery } from '@tanstack/react-query';
import {
	ProgressBar,
	// eslint-disable-next-line @wordpress/no-unsafe-wp-apis
	__experimentalVStack as VStack,
} from '@wordpress/components';
import { __, sprintf } from '@wordpress/i18n';
import { useEffect } from 'react';
import { backupDownloadProgressQuery } from '../../data/query-options';
 
interface DownloadProgressProps {
	downloadId: number;
	onDownloadComplete: ( downloadUrl: string, fileSizeBytes?: string ) => void;
	onDownloadError: () => void;
}
 
function DownloadProgress( {
	downloadId,
	onDownloadComplete,
	onDownloadError,
}: DownloadProgressProps ) {
	const { data: downloadProgress, error: downloadQueryError } = useQuery( {
		...backupDownloadProgressQuery( downloadId ),
		enabled: !! downloadId,
		// Poll every 1.5s while the URL is pending. Stop on error or once
		// the URL lands — the parent transitions the state machine and
		// this component unmounts.
		refetchInterval: query => {
			const { data, error } = query.state;
			if ( data?.error || error ) {
				return false;
			}
			if ( ! data?.url ) {
				return 1500;
			}
			return false;
		},
	} );
 
	useEffect( () => {
		if ( downloadProgress?.url ) {
			onDownloadComplete( downloadProgress.url, downloadProgress.bytes_formatted );
		} else if ( downloadProgress?.error || downloadQueryError ) {
			onDownloadError();
		}
	}, [
		downloadProgress?.url,
		downloadProgress?.bytes_formatted,
		downloadProgress?.error,
		onDownloadComplete,
		onDownloadError,
		downloadQueryError,
	] );
 
	return (
		<VStack spacing={ 4 } alignment="center">
			<p>{ __( 'Initializing the download process', 'jetpack-backup-pkg' ) }</p>
			<p style={ { color: '#757575', fontSize: 13 } }>
				{ sprintf(
					/* translators: %d is the download completion percentage. */
					__( '%d%% completed', 'jetpack-backup-pkg' ),
					downloadProgress?.progress ?? 0
				) }
			</p>
			<ProgressBar value={ downloadProgress?.progress ?? 0 } />
		</VStack>
	);
}
 
export default DownloadProgress;