import React, { useContext, useState } from 'react'; import { InitialValuesType } from './types'; import { compressImage } from './service'; import ToolContent from '@components/ToolContent'; import ToolImageInput from '@components/input/ToolImageInput'; import { ToolComponentProps } from '@tools/defineTool'; import ToolFileResult from '@components/result/ToolFileResult'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; import { Box } from '@mui/material'; import Typography from '@mui/material/Typography'; import { CustomSnackBarContext } from '../../../../../contexts/CustomSnackBarContext'; import { updateNumberField } from '@utils/string'; const initialValues: InitialValuesType = { maxFileSizeInMB: 1.0, quality: 80 }; export default function CompressImage({ title }: ToolComponentProps) { const [input, setInput] = useState(null); const [result, setResult] = useState(null); const [isProcessing, setIsProcessing] = useState(false); const [originalSize, setOriginalSize] = useState(null); // Store original file size const [compressedSize, setCompressedSize] = useState(null); // Store compressed file size const { showSnackBar } = useContext(CustomSnackBarContext); const compute = async (values: InitialValuesType, input: File | null) => { if (!input) return; setOriginalSize(input.size); try { setIsProcessing(true); const compressed = await compressImage(input, values); if (compressed) { setResult(compressed); setCompressedSize(compressed.size); } else { showSnackBar('Failed to compress image. Please try again.', 'error'); } } catch (err) { console.error('Error in compression:', err); } finally { setIsProcessing(false); } }; return ( } resultComponent={ } initialValues={initialValues} getGroups={({ values, updateField }) => [ { title: 'Compression options', component: ( updateNumberField(value, 'maxFileSizeInMB', updateField) } value={values.maxFileSizeInMB} /> updateNumberField(value, 'quality', updateField) } value={values.quality} /> ) }, { title: 'File sizes', component: ( {originalSize !== null && ( Original Size: {(originalSize / 1024).toFixed(2)} KB )} {compressedSize !== null && ( Compressed Size: {(compressedSize / 1024).toFixed(2)} KB )} ) } ]} compute={compute} setInput={setInput} /> ); }