All files / src/app/teacher-page/components/settings ChangePhoto.jsx

72.85% Statements 51/70
75% Branches 15/20
41.66% Functions 10/24
79.03% Lines 49/62

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221                              10x   10x 10x   10x 10x 10x   10x       10x 2x 2x 2x 2x 2x   2x 2x           10x 1x 1x 1x 1x 1x 1x                                         10x 2x 2x 2x   2x 1x 1x 1x 1x 1x 1x 1x 1x                                       1x 1x 1x 1x 1x 1x 1x 1x                                           10x 10x 2x                     8x                                                 10x         10x                                                                                            
import * as React from "react";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import { Alert, Box, IconButton, Typography } from "@mui/material";
import DefaultPhoto from "@/assets/default_image.png";
import { useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useSnackbar } from "notistack";
import { _addProfilePicture, _updateProfilePicture, _deleteProfilePicture } from "@/store/slices/teacher/TeacherData";
import CloseIcon from "@mui/icons-material/Close";
 
export default function ChangePhoto({ showDialog, setShowDialog, onPhotoUpdated }) {
    const { uploadPhotoHasErrors, uploadPhotoIsLoading, teacherData } = useSelector((state) => state.TeacherData);
 
    const dispatch = useDispatch();
    const { enqueueSnackbar, closeSnackbar } = useSnackbar();
 
    const inputRef = useRef(null);
    const [photo, setPhoto] = useState(""); //for displaying in browser
    const [selectedPhoto, setSelectedPhoto] = useState(null); //for sending payload
 
    const browseImage = () => {
        inputRef.current.click();
    };
 
    const handleChange = (event) => {
        try {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onloadend = () => {
                setPhoto(reader.result);
            };
            setSelectedPhoto(file);
            Eif (file) reader.readAsDataURL(file);
        } catch (error) {
            console.log(error);
        }
    };
 
    const handleDelete = () => {
        dispatch(_deleteProfilePicture()).then((response) => {
            if (!response.error) {
                setPhoto("");
                setSelectedPhoto(null);
                setShowDialog(false);
                enqueueSnackbar("Photo successfully deleted", {
                    variant: "success",
                    action: (key) => (
                        <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                            <CloseIcon fontSize="small" />
                        </IconButton>
                    ),
                });
            } else E{
                enqueueSnackbar("Invalid image upload", {
                    variant: "error",
                    action: (key) => (
                        <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                            <CloseIcon fontSize="small" />
                        </IconButton>
                    ),
                });
            }
        });
    };
 
    const clickSave = () => {
        const formData = new FormData();
        formData.append("file", selectedPhoto);
        const action = teacherData?.profile_picture ? _updateProfilePicture : _addProfilePicture;
 
        if (teacherData?.profile_picture) {
            dispatch(action(formData)).then((response) => {
                if (!response.error) {
                    onPhotoUpdated?.(photo);
                    window.dispatchEvent(new CustomEvent("profilePhotoUpdated", { detail: photo }));
                    setPhoto("");
                    setSelectedPhoto(null);
                    setShowDialog(false);
                    enqueueSnackbar("Photo successfully updated", {
                        variant: "success",
                        action: (key) => (
                            <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                                <CloseIcon fontSize="small" />
                            </IconButton>
                        ),
                    });
                } else E{
                    enqueueSnackbar("Invalid image upload", {
                        variant: "error",
                        action: (key) => (
                            <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                                <CloseIcon fontSize="small" />
                            </IconButton>
                        ),
                    });
                }
            });
        } else {
            dispatch(action(formData)).then((response) => {
                if (!response.error) {
                    onPhotoUpdated?.(photo);
                    window.dispatchEvent(new CustomEvent("profilePhotoUpdated", { detail: photo }));
                    setPhoto("");
                    setSelectedPhoto(null);
                    setShowDialog(false);
                    enqueueSnackbar("Photo successfully added", {
                        variant: "success",
                        action: (key) => (
                            <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                                <CloseIcon fontSize="small" />
                            </IconButton>
                        ),
                    });
                } else E{
                    enqueueSnackbar("Invalid image upload", {
                        variant: "error",
                        action: (key) => (
                            <IconButton size="small" color="inherit" onClick={() => closeSnackbar(key)}>
                                <CloseIcon fontSize="small" />
                            </IconButton>
                        ),
                    });
                }
            });
        }
    };
 
    const photoActions = () => {
        if (photo) {
            return (
                <React.Fragment>
                    <Button sx={{ width: "150px" }} variant="outlined" color="primary" onClick={browseImage}>
                        Change
                    </Button>
                    <Button sx={{ width: "150px" }} variant="contained" color="primary" onClick={clickSave}>
                        Save
                    </Button>
                </React.Fragment>
            );
        } else {
            return (
                <>
                    <Button
                        id="teacher-settings-button-upload"
                        sx={{ width: "150px" }}
                        variant="outlined"
                        color="primary"
                        onClick={handleDelete}
                    >
                        Delete
                    </Button>
                    <Button
                        id="teacher-settings-button-upload"
                        sx={{ width: "150px" }}
                        variant="contained"
                        color="primary"
                        onClick={browseImage}
                    >
                        Upload
                    </Button>
                </>
            );
        }
    };
 
    const clickCancel = () => {
        setPhoto(null);
        setShowDialog(false);
    };
 
    return (
        <React.Fragment>
            <input
                ref={inputRef}
                id="teacher-settings-input-upload"
                type="file"
                accept="image/*"
                hidden
                onChange={handleChange}
            />
            <Dialog
                open={showDialog}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
                fullWidth
            >
                <DialogTitle
                    id="alert-dialog-title"
                    sx={{
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                    }}
                >
                    <Typography variant="body1">Edit Photo</Typography>
                </DialogTitle>
                <DialogContent dividers>
                    {uploadPhotoHasErrors && <Alert severity="error">{uploadPhotoHasErrors}</Alert>}
                    <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", objectFit: "cover" }}>
                        <img
                            style={{ width: "8rem", height: "8rem", borderRadius: "50%" }}
                            src={photo ? photo : teacherData?.profile_picture || DefaultPhoto}
                            alt="Profile"
                        />
                    </Box>
                </DialogContent>
                <DialogActions sx={{ display: "flex", justifyContent: "space-between" }}>
                    <Button sx={{ width: "150px" }} variant="inherit" onClick={clickCancel}>
                        Cancel
                    </Button>
                    {photoActions()}
                </DialogActions>
            </Dialog>
        </React.Fragment>
    );
}