Refactored some of the code
This commit is contained in:
1 parent
bef0ad797b
commit
5807990342
7 files changed
+100
-148
No files matched your search
@@ -1,12 +1,13 @@
|
||||
import { Avatar as MuiAvatar } from "@mui/material";
|
||||
import PropTypes from "prop-types";
|
||||
import { useSelector } from "react-redux";
|
||||
import { useEffect, useState } from "react";
|
||||
import { bufferTo64 } from "../../Utils/fileUtils";
|
||||
|
||||
/**
|
||||
* @component
|
||||
* @param {Object} props
|
||||
* @param {string} props.src - Path to image for avatar
|
||||
* @param {string} props.firstName - The users first name
|
||||
* @param {string} props.lastName - The users last name
|
||||
* @param {boolean} props.small - Specifies if avatar should be large
|
||||
* @param {Object} [props.sx] - Additional styles to apply to the button.
|
||||
* @returns {JSX.Element}
|
||||
@@ -15,29 +16,57 @@ import PropTypes from "prop-types";
|
||||
* <Avatar src="assets/img" first="Alex" last="Holliday" small />
|
||||
*/
|
||||
|
||||
const Avatar = ({ src, firstName, lastName, small, sx }) => {
|
||||
const borderColor = "#F0F2F4";
|
||||
const smallStyle = small ? { width: 32, height: 32 } : {};
|
||||
const Avatar = ({ src, small, sx }) => {
|
||||
const { user } = useSelector((state) => state.auth);
|
||||
|
||||
const style = small ? { width: 25, height: 25 } : { width: 64, height: 64 };
|
||||
const border = small ? 1 : 3;
|
||||
|
||||
const [image, setImage] = useState();
|
||||
useEffect(() => {
|
||||
const fetchImage = async () => {
|
||||
if (user.profileImage.data && user.profileImage.contentType) {
|
||||
try {
|
||||
const base64 = await bufferTo64(user.profileImage.data);
|
||||
setImage(base64);
|
||||
} catch (error) {
|
||||
console.error("Error converting buffer to base64:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
fetchImage();
|
||||
}, [user]);
|
||||
|
||||
return (
|
||||
<MuiAvatar
|
||||
alt={`${firstName} ${lastName}`}
|
||||
src={src}
|
||||
alt={`${user?.firstname} ${user?.lastname}`}
|
||||
src={src ? src : user?.profileImage ? image : ""}
|
||||
sx={{
|
||||
fontSize: small ? "12px" : "20px",
|
||||
display: "inline-flex",
|
||||
border: `0.2rem solid ${borderColor}`,
|
||||
...smallStyle,
|
||||
...sx
|
||||
"&::before": {
|
||||
content: `""`,
|
||||
position: "absolute",
|
||||
top: "0",
|
||||
left: "0",
|
||||
width: `calc(100% - ${border * 2}px)`,
|
||||
height: `calc(100% - ${border * 2}px)`,
|
||||
border: `${border}px solid rgba(255,255,255,0.2)`,
|
||||
borderRadius: "50%",
|
||||
},
|
||||
...style,
|
||||
...sx,
|
||||
}}
|
||||
>
|
||||
{src === undefined ? `${firstName[0]}${lastName[0]}` : null}
|
||||
{src === undefined
|
||||
? `${user.firstname?.charAt(0)}${user.lastname?.charAt(0)}`
|
||||
: null}
|
||||
</MuiAvatar>
|
||||
);
|
||||
};
|
||||
|
||||
Avatar.propTypes = {
|
||||
src: PropTypes.string,
|
||||
firstName: PropTypes.string.isRequired,
|
||||
lastName: PropTypes.string.isRequired,
|
||||
small: PropTypes.bool,
|
||||
sx: PropTypes.object,
|
||||
};
|
||||
|
||||
@@ -5,12 +5,6 @@
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.icon-button-avatar {
|
||||
width: 25px;
|
||||
height: 25px;
|
||||
margin-right: var(--env-var-spacing-1);
|
||||
}
|
||||
|
||||
.icon-button-toggle-title {
|
||||
font-size: var(--env-var-font-size-medium);
|
||||
color: var(--env-var-color-5);
|
||||
|
||||
@@ -8,7 +8,7 @@ import Typography from "@mui/material/Typography";
|
||||
import Menu from "@mui/material/Menu";
|
||||
import MenuIcon from "@mui/icons-material/Menu";
|
||||
import Container from "@mui/material/Container";
|
||||
import Avatar from "@mui/material/Avatar";
|
||||
import Avatar from "../Avatar";
|
||||
import Tooltip from "@mui/material/Tooltip";
|
||||
import MenuItem from "@mui/material/MenuItem";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
@@ -151,12 +151,7 @@ function NavBar() {
|
||||
sx={{ p: 0 }}
|
||||
>
|
||||
<div className="icon-button-toggle">
|
||||
<Avatar
|
||||
alt="Remy Sharp"
|
||||
src="/static/images/avatar/2.jpg"
|
||||
className="icon-button-avatar"
|
||||
style={{ width: "25px", height: "25px" }}
|
||||
/>
|
||||
<Avatar small={true} sx={{ mr: "8px" }} />
|
||||
<div className="icon-button-toggle-title">
|
||||
{authState.user.firstname} {authState.user.lastname}
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,7 @@ import { update } from "../../../Features/Auth/authSlice";
|
||||
import ImageField from "../../TextFields/Image";
|
||||
import ImageIcon from "@mui/icons-material/Image";
|
||||
import ProgressUpload from "../../ProgressBars";
|
||||
import { bufferTo64, formatBytes } from "../../../Utils/fileUtils";
|
||||
import { formatBytes } from "../../../Utils/fileUtils";
|
||||
|
||||
/**
|
||||
* ProfilePanel component displays a form for editing user profile information
|
||||
@@ -34,17 +34,17 @@ const ProfilePanel = () => {
|
||||
const idToName = {
|
||||
"edit-first-name": "firstname",
|
||||
"edit-last-name": "lastname",
|
||||
//Disabled for now, will revisit in the future
|
||||
// Disabled for now, will revisit in the future
|
||||
// "edit-email": "email",
|
||||
};
|
||||
const [localData, setLocalData] = useState({
|
||||
firstname: user.firstname,
|
||||
lastname: user.lastname,
|
||||
//Disabled for now, will revisit in the future
|
||||
// Disabled for now, will revisit in the future
|
||||
// email: user.email,
|
||||
//TODO - upload picture
|
||||
profileImage: { file: user.profileImage },
|
||||
profileImage: user.profileImage,
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState({});
|
||||
const clearError = (err) => {
|
||||
setErrors((prev) => {
|
||||
@@ -53,29 +53,10 @@ const ProfilePanel = () => {
|
||||
return updatedErrors;
|
||||
});
|
||||
};
|
||||
|
||||
const [isOpen, setIsOpen] = useState("");
|
||||
const isModalOpen = (name) => isOpen === name;
|
||||
|
||||
//maybe move this to Avatar component?
|
||||
const [image, setImage] = useState("");
|
||||
useEffect(() => {
|
||||
const fetchImage = async () => {
|
||||
if (
|
||||
localData.profileImage.file &&
|
||||
localData.profileImage.file.contentType
|
||||
) {
|
||||
try {
|
||||
const base64 = await bufferTo64(localData.profileImage.file.data);
|
||||
setImage(base64);
|
||||
} catch (error) {
|
||||
console.error("Error converting buffer to base64:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
fetchImage();
|
||||
}, [localData.profileImage.file]);
|
||||
|
||||
const handleChange = (event) => {
|
||||
const { value, id } = event.target;
|
||||
const name = idToName[id];
|
||||
@@ -84,71 +65,37 @@ const ProfilePanel = () => {
|
||||
[name]: value,
|
||||
}));
|
||||
|
||||
const validation = editProfileValidation.validate(
|
||||
{ [name]: value },
|
||||
{ abortEarly: false }
|
||||
);
|
||||
|
||||
setErrors((prev) => {
|
||||
const updatedErrors = { ...prev };
|
||||
|
||||
if (validation.error) {
|
||||
updatedErrors[name] = validation.error.details[0].message;
|
||||
} else {
|
||||
delete updatedErrors[name];
|
||||
}
|
||||
return updatedErrors;
|
||||
});
|
||||
validateField({ [name]: value }, editProfileValidation, name);
|
||||
};
|
||||
|
||||
//holds file info
|
||||
const [file, setFile] = useState({});
|
||||
const [progress, setProgress] = useState({ value: 0, isLoading: false });
|
||||
const intervalRef = useRef(null);
|
||||
const handlePicture = (event) => {
|
||||
const pic = event.target.files[0];
|
||||
//reset errors if any
|
||||
clearError("picture");
|
||||
let error = validateField(
|
||||
{ type: pic.type, size: pic.size },
|
||||
imageValidation
|
||||
);
|
||||
if (error) return;
|
||||
|
||||
if (pic) {
|
||||
setProgress((prev) => ({ ...prev, isLoading: true }));
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
profileImage: {
|
||||
...prev.profileImage,
|
||||
name: pic.name,
|
||||
type: pic.type,
|
||||
size: formatBytes(pic.size),
|
||||
toUpload: pic,
|
||||
},
|
||||
}));
|
||||
|
||||
const { error } = imageValidation.validate(
|
||||
{
|
||||
type: pic.type,
|
||||
size: pic.size,
|
||||
},
|
||||
{ abortEarly: false }
|
||||
);
|
||||
|
||||
if (error) {
|
||||
setErrors((prev) => ({
|
||||
...prev,
|
||||
["picture"]: error.details[0].message,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
setFile({ pic: pic, name: pic.name, size: formatBytes(pic.size) });
|
||||
|
||||
//read image
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
reader.onload = () => {
|
||||
const base64 = reader.result;
|
||||
setLocalData((prev) => ({
|
||||
setFile((prev) => ({
|
||||
...prev,
|
||||
profileImage: {
|
||||
...prev.profileImage,
|
||||
src: base64,
|
||||
},
|
||||
src: base64,
|
||||
}));
|
||||
|
||||
//TODO - potentitally remove once image compression functions are implemented above
|
||||
intervalRef.current = setInterval(() => {
|
||||
const buffer = 8;
|
||||
const buffer = 12;
|
||||
setProgress((prev) => {
|
||||
if (prev.value + buffer >= 100) {
|
||||
clearInterval(intervalRef.current);
|
||||
@@ -161,36 +108,42 @@ const ProfilePanel = () => {
|
||||
reader.readAsDataURL(pic);
|
||||
}
|
||||
};
|
||||
|
||||
const validateField = (toValidate, schema, name = "picture") => {
|
||||
const { error } = schema.validate(toValidate, { abortEarly: false });
|
||||
setErrors((prev) => {
|
||||
const prevErrors = { ...prev };
|
||||
if (error) prevErrors[name] = error.details[0].message;
|
||||
else delete prevErrors[name];
|
||||
return prevErrors;
|
||||
});
|
||||
if (error) return true;
|
||||
};
|
||||
|
||||
const removePicture = () => {
|
||||
clearError("picture");
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
profileImage: { file: "" },
|
||||
}));
|
||||
setFile({});
|
||||
//interrupt interval if image upload is canceled prior to completing the process
|
||||
clearInterval(intervalRef.current);
|
||||
setProgress({ value: 0, isLoading: false });
|
||||
};
|
||||
const closePictureModal = () => {
|
||||
clearError("picture");
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
profileImage: { file: user.profileImage },
|
||||
}));
|
||||
//interrupt interval if modal closes prior to completing the process
|
||||
clearInterval(intervalRef.current);
|
||||
setProgress({ value: 0, isLoading: false });
|
||||
removePicture();
|
||||
setIsOpen("");
|
||||
};
|
||||
const handleUpdatePicture = () => {
|
||||
setProgress({ value: 0, isLoading: false });
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
profileImage: file.pic,
|
||||
}));
|
||||
setFile({});
|
||||
setIsOpen("");
|
||||
};
|
||||
const handleDeletePicture = () => {
|
||||
setImage(null);
|
||||
setLocalData((prev) => ({
|
||||
...prev,
|
||||
profileImage: { file: "", toUpload: "" },
|
||||
profileImage: "",
|
||||
}));
|
||||
};
|
||||
//TODO - implement delete account function
|
||||
@@ -200,17 +153,13 @@ const ProfilePanel = () => {
|
||||
if (
|
||||
localData.firstname === user.firstname &&
|
||||
localData.lastname === user.lastname &&
|
||||
localData.profileImage.toUpload === user.profileImage
|
||||
localData.profileImage === user.profileImage
|
||||
) {
|
||||
//TODO - add toast(profile data is unchanged) and maybe disable button
|
||||
return;
|
||||
}
|
||||
|
||||
const toUpdate = {
|
||||
...localData,
|
||||
profileImage: localData.profileImage.toUpload,
|
||||
};
|
||||
dispatch(update({ authToken, toUpdate }));
|
||||
dispatch(update({ authToken, localData }));
|
||||
//TODO - add toast confirmation
|
||||
};
|
||||
|
||||
@@ -299,19 +248,8 @@ const ProfilePanel = () => {
|
||||
</Stack>
|
||||
<Stack className="row-stack" direction="row" alignItems="center">
|
||||
<Avatar
|
||||
src={
|
||||
localData.profileImage?.src
|
||||
? localData.profileImage?.src
|
||||
: image
|
||||
? image
|
||||
: "/static/images/avatar/2.jpg"
|
||||
}
|
||||
firstName={user?.firstname}
|
||||
lastName={user?.lastname}
|
||||
src={file?.src ? file.src : ""}
|
||||
sx={{
|
||||
width: "64px",
|
||||
height: "64px",
|
||||
border: "none",
|
||||
mr: "8px",
|
||||
}}
|
||||
/>
|
||||
@@ -450,21 +388,15 @@ const ProfilePanel = () => {
|
||||
</Typography>
|
||||
<ImageField
|
||||
id="update-profile-picture"
|
||||
picture={
|
||||
localData.profileImage?.src
|
||||
? localData.profileImage?.src
|
||||
: localData.profileImage?.file
|
||||
? image
|
||||
: ""
|
||||
}
|
||||
picture={file?.src ? file?.src : ""}
|
||||
loading={progress.isLoading && progress.value !== 100}
|
||||
onChange={handlePicture}
|
||||
/>
|
||||
{progress.isLoading || progress.value !== 0 ? (
|
||||
{progress.isLoading || progress.value !== 0 || errors["picture"] ? (
|
||||
<ProgressUpload
|
||||
icon={<ImageIcon />}
|
||||
label={localData.profileImage?.name}
|
||||
size={localData.profileImage?.size}
|
||||
label={file.name}
|
||||
size={file.size}
|
||||
progress={progress.value}
|
||||
onClick={removePicture}
|
||||
error={errors["picture"]}
|
||||
|
||||
@@ -41,7 +41,7 @@ export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
|
||||
export const update = createAsyncThunk(
|
||||
"auth/update",
|
||||
async (data, thunkApi) => {
|
||||
const { authToken: token, toUpdate: form } = data;
|
||||
const { authToken: token, localData: form } = data;
|
||||
const user = jwtDecode(token);
|
||||
try {
|
||||
//1.5s delay to show loading spinner
|
||||
|
||||
@@ -29,7 +29,7 @@ import AddIcon from "@mui/icons-material/Add";
|
||||
import Divider from "@mui/material/Divider";
|
||||
import UploadIcon from "@mui/icons-material/Upload";
|
||||
import SendIcon from "@mui/icons-material/Send";
|
||||
import ImageIcon from '@mui/icons-material/Image';
|
||||
import ImageIcon from "@mui/icons-material/Image";
|
||||
|
||||
// Redux
|
||||
import { useSelector } from "react-redux";
|
||||
@@ -423,7 +423,11 @@ const Demo = () => {
|
||||
</Stack>
|
||||
<Divider sx={{ margin: `${theme.spacing(2)}` }} />
|
||||
<Stack justifyContent="center" alignItems="center">
|
||||
<ProgressUpload icon={<ImageIcon />} label="image.jpg" size="2 MB"/>
|
||||
<ProgressUpload icon={<ImageIcon />} label="image.jpg" size="2 MB" />
|
||||
</Stack>
|
||||
<Divider sx={{ margin: `${theme.spacing(2)}` }} />
|
||||
<Stack justifyContent="center" alignItems="center">
|
||||
<Avatar />
|
||||
</Stack>
|
||||
<Divider sx={{ margin: `${theme.spacing(2)}` }} />
|
||||
</div>
|
||||
|
||||
@@ -21,5 +21,3 @@ export const bufferTo64 = (bufferData) => {
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user