import LinkIcon from "@mui/icons-material/Link"; import UploadIcon from "@mui/icons-material/Upload"; import { Button } from "@mui/material"; import React from "react"; import { Area } from "react-easy-crop"; import { ServerApi } from "../../api/ServerApi"; import { ImageCropperDialog } from "../../dialogs/ImageCropperDialog"; import { useAlert } from "../../hooks/context_providers/AlertDialogProvider"; import getCroppedImg from "../../utils/crop_image"; import { isDebug } from "../../utils/debug_utils"; import { selectFileToUpload } from "../../utils/files_utils"; export function UploadPhotoButton(p: { label: string; onPhotoSelected: (b: Blob) => Promise; aspect?: number; }): React.ReactElement { const [processing, setProcessing] = React.useState(false); const [imageBlob, setImageBlob] = React.useState(); const [imageURL, setImageURL] = React.useState(); const alert = useAlert(); const uploadPhoto = async () => { try { const file = await selectFileToUpload({ allowedTypes: ServerApi.Config.constraints.photo_allowed_types, maxSize: ServerApi.Config.constraints.photo_max_size, }); if (file === null) return; const tempURL = URL.createObjectURL(file); setImageBlob(file); setImageURL(tempURL); } catch (e) { console.error(e); alert(`Échec de l'envoi de l'image ! (${e})`); } }; const uploadPhotoFromURL = async () => { const URL = prompt("Image URL ?"); if (URL === null || URL.length === 0) return; setImageURL(URL); }; const cancelCrop = () => { setImageURL(undefined); }; const submitCrop = async (a: Area | undefined) => { setProcessing(true); try { let blob = imageBlob!; if (a) { blob = await getCroppedImg(imageURL!, a!); } await p.onPhotoSelected(blob); setImageBlob(undefined); setImageURL(undefined); } catch (e) { console.error(e); alert("Echec du traitement de la photo !"); } setProcessing(false); }; return ( <> {/* Upload button */} {/* Upload button (from URL) */}{" "} {isDebug() && ( )}{" "} {/* Crop image dialog */} {imageURL && ( )} ); }