Refactored code and hooked up picture to localState

This commit is contained in:
Daniel Cojocea committed 2024-07-03 13:04:46 -04:00
1 parent 75d16b749d
commit c1d0c24f78
5 files changed
+135 -97

No files matched your search

+2 -1
View File
@@ -17,7 +17,8 @@
padding-left: 2px; padding-left: 2px;
} }
.progress-bar-container:has(p.input-error){ .progress-bar-container:has(p.input-error){
border-color: var(--env-var-color-24); border-color: var(--env-var-color-19);
background-color: var(--env-var-color-21);
padding: 8px var(--env-var-spacing-1-plus); padding: 8px var(--env-var-spacing-1-plus);
} }
.progress-bar-container p.input-error{ .progress-bar-container p.input-error{
@@ -94,6 +94,9 @@ const ProgressUpload = ({
} }
: { : {
ml: "auto", ml: "auto",
"&:focus": {
outline: "none",
},
} }
} }
> >
@@ -1,5 +1,5 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useState } from "react"; import { useRef, useState } from "react";
import TabPanel from "@mui/lab/TabPanel"; import TabPanel from "@mui/lab/TabPanel";
import { Box, Divider, Modal, Stack, Typography } from "@mui/material"; import { Box, Divider, Modal, Stack, Typography } from "@mui/material";
import ButtonSpinner from "../../ButtonSpinner"; import ButtonSpinner from "../../ButtonSpinner";
@@ -16,6 +16,7 @@ import { update } from "../../../Features/Auth/authSlice";
import ImageField from "../../TextFields/Image"; import ImageField from "../../TextFields/Image";
import ImageIcon from "@mui/icons-material/Image"; import ImageIcon from "@mui/icons-material/Image";
import ProgressUpload from "../../ProgressBars"; import ProgressUpload from "../../ProgressBars";
import { bytesToUrl, checkImage, formatBytes } from "../../../Utils/fileUtils";
/** /**
* ProfilePanel component displays a form for editing user profile information * ProfilePanel component displays a form for editing user profile information
@@ -42,12 +43,18 @@ const ProfilePanel = () => {
//Disabled for now, will revisit in the future //Disabled for now, will revisit in the future
// email: user.email, // email: user.email,
//TODO - upload picture //TODO - upload picture
profilePicUrl: "placeholder", profilePicUrl: { src: user.profilePicUrl },
}); });
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const clearError = (err) => {
setErrors((prev) => {
const updatedErrors = { ...prev };
if (updatedErrors[err]) delete updatedErrors[err];
return updatedErrors;
});
};
const [isOpen, setIsOpen] = useState(""); const [isOpen, setIsOpen] = useState("");
const isModalOpen = (name) => isOpen === name; const isModalOpen = (name) => isOpen === name;
const [loading, setLoading] = useState(false);
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
@@ -73,90 +80,84 @@ const ProfilePanel = () => {
return updatedErrors; return updatedErrors;
}); });
}; };
const [progress, setProgress] = useState({ value: 0, isLoading: false });
//TODO - add setPicture state to localData const intervalRef = useRef(null);
const [picture, setPicture] = useState();
const [uploadProgress, setUploadProgress] = useState(0);
const [isUploading, setIsUploading] = useState(false);
const handlePicture = (event) => { const handlePicture = (event) => {
clearError("picture");
const pic = event.target.files[0]; const pic = event.target.files[0];
console.log(pic); //reset errors if any
//TODO - add setPicture state to localData clearError("picture");
setPicture({ name: pic.name, type: pic.type, size: formatBytes(pic.size) }); if (pic) {
setIsUploading(true); setProgress((prev) => ({ ...prev, isLoading: true }));
setLocalData((prev) => ({
...prev,
profilePicUrl: {
name: pic.name,
type: pic.type,
size: formatBytes(pic.size),
src: "",
},
}));
const { error } = imageValidation.validate( const { error } = imageValidation.validate(
{ {
type: pic.type, type: pic.type,
size: pic.size, size: pic.size,
}, },
{ abortEarly: false } { abortEarly: false }
); );
if (error) { if (error) {
setErrors((prev) => { setErrors((prev) => ({
const updatedErrors = { ...prev }; ...prev,
updatedErrors["picture"] = error.details[0].message; ["picture"]: error.details[0].message,
return updatedErrors; }));
}); return;
return;
}
setTimeout(() => {
//TODO - add setPicture state to localData
setPicture((prev) => ({ ...prev, src: URL.createObjectURL(pic) }));
}, 1500);
let progress = 0;
const interval = setInterval(() => {
progress += 10;
setUploadProgress(progress);
if (progress >= 100) {
clearInterval(interval);
} }
}, 150);
};
const formatBytes = (bytes) => {
if (bytes === 0) return "0 Bytes";
const megabytes = bytes / (1024 * 1024);
return megabytes.toFixed(2) + " MB";
};
const clearError = (err) => {
setErrors((prev) => {
const updatedErrors = { ...prev };
if (updatedErrors[err]) delete updatedErrors[err];
return updatedErrors;
});
};
const handleCancelUpload = () => {
//TODO - add setPicture state to localData
setPicture();
setUploadProgress(0);
setIsUploading(false);
clearError("picture");
};
const handleClosePictureModal = () => {
setIsOpen("");
setUploadProgress(0);
setIsUploading(false);
clearError("picture");
};
//TODO - revisit once localData is set up properly const reader = new FileReader();
const handleDeletePicture = () => { reader.onloadend = () => {
setLoading(true); const arrayBuffer = reader.result;
setTimeout(() => { const bytes = new Uint8Array(arrayBuffer);
//TODO - add setPicture state to localData setLocalData((prev) => ({
setPicture(null); ...prev,
setLoading(false); profilePicUrl: {
}, 2000); ...prev.profilePicUrl,
src: bytes,
},
}));
//TODO - potentitally remove once image compression functions are implemented above
intervalRef.current = setInterval(() => {
const buffer = 8;
setProgress((prev) => {
if (prev.value + buffer >= 100) {
clearInterval(intervalRef.current);
return { value: 100, isLoading: false };
}
return { ...prev, value: prev.value + buffer };
});
}, 150);
};
reader.readAsArrayBuffer(pic);
}
}; };
//TODO - implement update profile function const removePicture = () => {
const handleUpdatePicture = () => { clearError("picture");
setLocalData((prev) => ({
...prev,
profilePicUrl: { src: user.profilePicUrl },
}));
//interrupt interval if modal closes prior to completing the process
clearInterval(intervalRef.current);
setProgress({ value: 0, isLoading: false });
};
const closePictureModal = () => {
removePicture();
setIsOpen("");
};
const handleUpdatePicture = () => {
setProgress({ value: 0, isLoading: false });
setIsOpen(""); setIsOpen("");
setUploadProgress(0);
setIsUploading(false);
}; };
//TODO - implement delete account function //TODO - implement delete account function
const handleDeleteAccount = () => {}; const handleDeleteAccount = () => {};
@@ -261,7 +262,11 @@ const ProfilePanel = () => {
</Stack> </Stack>
<Stack className="row-stack" direction="row" alignItems="center"> <Stack className="row-stack" direction="row" alignItems="center">
<Avatar <Avatar
src={picture ? picture.src : "/static/images/avatar/2.jpg"} src={
localData.profilePicUrl
? bytesToUrl(localData.profilePicUrl?.src)
: "/static/images/avatar/2.jpg"
}
firstName={user?.firstname} firstName={user?.firstname}
lastName={user?.lastname} lastName={user?.lastname}
sx={{ sx={{
@@ -271,11 +276,10 @@ const ProfilePanel = () => {
mr: "8px", mr: "8px",
}} }}
/> />
<ButtonSpinner <Button
level="tertiary" level="tertiary"
label="Delete" label="Delete"
onClick={handleDeletePicture} onClick={removePicture}
isLoading={loading}
/> />
<Button <Button
level="tertiary" level="tertiary"
@@ -301,7 +305,9 @@ const ProfilePanel = () => {
onClick={handleSaveProfile} onClick={handleSaveProfile}
isLoading={isLoading} isLoading={isLoading}
loadingText="Saving..." loadingText="Saving..."
disabled={Object.keys(errors).length !== 0 && true} disabled={
Object.keys(errors).length !== 0 && !errors?.picture && true
}
sx={{ sx={{
paddingX: "40px", paddingX: "40px",
}} }}
@@ -381,7 +387,7 @@ const ProfilePanel = () => {
aria-labelledby="modal-update-picture" aria-labelledby="modal-update-picture"
aria-describedby="update-profile-picture" aria-describedby="update-profile-picture"
open={isModalOpen("picture")} open={isModalOpen("picture")}
onClose={handleClosePictureModal} onClose={closePictureModal}
> >
<Stack <Stack
sx={{ sx={{
@@ -405,16 +411,17 @@ const ProfilePanel = () => {
</Typography> </Typography>
<ImageField <ImageField
id="update-profile-picture" id="update-profile-picture"
picture={picture?.src} picture={bytesToUrl(localData.profilePicUrl?.src)}
loading={progress.isLoading && progress.value !== 100}
onChange={handlePicture} onChange={handlePicture}
/> />
{isUploading ? ( {progress.isLoading || progress.value !== 0 ? (
<ProgressUpload <ProgressUpload
icon={<ImageIcon />} icon={<ImageIcon />}
label={picture?.name} label={localData.profilePicUrl?.name}
size={picture?.size} size={localData.profilePicUrl?.size}
progress={uploadProgress} progress={progress.value}
onClick={handleCancelUpload} onClick={removePicture}
error={errors["picture"]} error={errors["picture"]}
/> />
) : ( ) : (
@@ -427,17 +434,22 @@ const ProfilePanel = () => {
disabled disabled
sx={{ mr: "auto" }} sx={{ mr: "auto" }}
/> />
<ButtonSpinner <Button
level="tertiary" level="tertiary"
label="Remove" label="Remove"
onClick={handleCancelUpload} onClick={removePicture}
isLoading={loading}
/> />
<ButtonSpinner <ButtonSpinner
level="primary" level="primary"
label="Update" label="Update"
onClick={handleUpdatePicture} onClick={handleUpdatePicture}
isLoading={isLoading} isLoading={isLoading}
disabled={
(Object.keys(errors).length !== 0 && errors?.picture) ||
progress.value !== 100
? true
: false
}
/> />
</Stack> </Stack>
</Stack> </Stack>
@@ -4,6 +4,7 @@ import { Box, IconButton, Stack, TextField, Typography } from "@mui/material";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import CloudUploadIcon from "@mui/icons-material/CloudUpload"; import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import "./index.css"; import "./index.css";
import { checkImage } from "../../../Utils/fileUtils";
/** /**
* @param {Object} props - The component props. * @param {Object} props - The component props.
@@ -13,7 +14,7 @@ import "./index.css";
* @returns {JSX.Element} The rendered component. * @returns {JSX.Element} The rendered component.
*/ */
const ImageField = ({ id, picture, onChange }) => { const ImageField = ({ id, picture, loading, onChange }) => {
const theme = useTheme(); const theme = useTheme();
const [isDragging, setIsDragging] = useState(false); const [isDragging, setIsDragging] = useState(false);
@@ -26,7 +27,7 @@ const ImageField = ({ id, picture, onChange }) => {
return ( return (
<> <>
{!picture ? ( {!checkImage(picture) || loading ? (
<> <>
<Box <Box
className="image-field-wrapper" className="image-field-wrapper"
+21
View File
@@ -0,0 +1,21 @@
import { useMemo } from "react";
export const bytesToUrl = (bytes) => {
return useMemo(() => {
const blob = new Blob([bytes], { type: "image/jpeg" });
const url = URL.createObjectURL(blob);
return url;
}, [bytes]);
};
export const formatBytes = (bytes) => {
if (bytes === 0) return "0 Bytes";
const megabytes = bytes / (1024 * 1024);
return megabytes.toFixed(2) + " MB";
};
export const checkImage = (url) => {
const img = new Image();
img.src = url;
return img.naturalWidth !==0;
}