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