diff --git a/Client/src/App.jsx b/Client/src/App.jsx index 405371db2..0c3b07232 100644 --- a/Client/src/App.jsx +++ b/Client/src/App.jsx @@ -39,6 +39,7 @@ function App() { const DetailsWithAdminProp = withAdminProp(Details); const PageSpeedWithAdminProp = withAdminProp(PageSpeed); const MaintenanceWithAdminProp = withAdminProp(Maintenance); + const SettingsWithAdminProp = withAdminProp(Settings); const mode = useSelector((state) => state.ui.mode); @@ -90,7 +91,7 @@ function App() { /> } + element={} /> { const theme = useTheme(); - const { text, light, border } = theme.palette[variant]; + const { text, bg, border } = theme.palette[variant]; const icon = icons[variant]; return ( @@ -46,7 +45,7 @@ const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => { padding: hasIcon ? theme.spacing(8) : `${theme.spacing(4)} ${theme.spacing(8)}`, - backgroundColor: light, + backgroundColor: bg, border: `solid 1px ${border}`, borderRadius: theme.shape.borderRadius, }} @@ -65,8 +64,8 @@ const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => { )} {hasIcon && isToast && ( + > + Dismiss + )} {isToast && ( diff --git a/Client/src/Components/Animated/PulseDot.jsx b/Client/src/Components/Animated/PulseDot.jsx index 38e956b50..9ac536fe6 100644 --- a/Client/src/Components/Animated/PulseDot.jsx +++ b/Client/src/Components/Animated/PulseDot.jsx @@ -41,8 +41,8 @@ const PulseDot = ({ color }) => { "&::after": { content: `""`, position: "absolute", - width: "6px", - height: "6px", + width: "7px", + height: "7px", borderRadius: "50%", backgroundColor: "white", top: "50%", diff --git a/Client/src/Components/BasicTable/index.jsx b/Client/src/Components/BasicTable/index.jsx index e2de29ae1..e9fbbadfd 100644 --- a/Client/src/Components/BasicTable/index.jsx +++ b/Client/src/Components/BasicTable/index.jsx @@ -13,6 +13,7 @@ import { Box, Typography, Stack, + Button, } from "@mui/material"; import { useDispatch, useSelector } from "react-redux"; import { setRowsPerPage } from "../../Features/UI/uiSlice"; @@ -21,7 +22,6 @@ import RightArrowDouble from "../../assets/icons/right-arrow-double.svg?react"; import LeftArrow from "../../assets/icons/left-arrow.svg?react"; import RightArrow from "../../assets/icons/right-arrow.svg?react"; import SelectorVertical from "../../assets/icons/selector-vertical.svg?react"; -import Button from "../Button"; import "./index.css"; /** * Component for pagination actions (first, previous, next, last). @@ -54,37 +54,37 @@ const TablePaginationActions = (props) => { return ( ); }; @@ -200,31 +200,12 @@ const BasicTable = ({ data, paginated, reversed, table }) => { return ( <> - + - + {data.cols.map((col) => ( - - {col.name} - + {col.name} ))} @@ -242,17 +223,7 @@ const BasicTable = ({ data, paginated, reversed, table }) => { onClick={row.handleClick ? row.handleClick : null} > {row.data.map((cell) => { - return ( - - {cell.data} - - ); + return {cell.data}; })} ); @@ -322,18 +293,14 @@ const BasicTable = ({ data, paginated, reversed, table }) => { sx={{ mt: theme.spacing(6), color: theme.palette.text.secondary, - "& button.MuiButtonBase-root, & .MuiSelect-select": { - border: 1, - borderColor: theme.palette.border.light, - borderRadius: theme.shape.borderRadius, - }, "& svg path": { stroke: theme.palette.text.tertiary, strokeWidth: 1.3, }, - "& button:not(.Mui-disabled):hover": { - backgroundColor: theme.palette.background.fill, - borderColor: theme.palette.background.fill, + "& .MuiSelect-select": { + border: 1, + borderColor: theme.palette.border.light, + borderRadius: theme.shape.borderRadius, }, }} /> diff --git a/Client/src/Components/Button/index.css b/Client/src/Components/Button/index.css deleted file mode 100644 index 63791d46b..000000000 --- a/Client/src/Components/Button/index.css +++ /dev/null @@ -1,33 +0,0 @@ -.MuiButtonBase-root.button-rotate90 svg { - transition: transform 500ms ease; -} -.MuiButtonBase-root.button-rotate90:hover svg { - transform: rotate(90deg); - transform-origin: center; -} - -.MuiButtonBase-root.button-rotate180 svg { - transition: transform 700ms ease; -} -.MuiButtonBase-root.button-rotate180:hover svg { - transform: rotate(180deg); - transform-origin: center; -} - -.MuiButtonBase-root.button-slideLeft { - padding-left: 45px; -} -.MuiButtonBase-root.button-slideLeft svg { - position: absolute; - left: 15px; - transition: left 250ms cubic-bezier(0.65, 0, 0.076, 1); -} -.MuiButtonBase-root.button-slideLeft:hover svg { - left: 11px; -} - -.MuiButtonBase-root.button-slideLeft:hover, -.MuiButtonBase-root.button-rotate180:hover, -.MuiButtonBase-root.button-rotate90:hover { - background-color: rgba(71, 84, 103, 0.08); -} diff --git a/Client/src/Components/Button/index.jsx b/Client/src/Components/Button/index.jsx deleted file mode 100644 index 4c59f8b47..000000000 --- a/Client/src/Components/Button/index.jsx +++ /dev/null @@ -1,108 +0,0 @@ -import { Button as MuiButton } from "@mui/material"; -import PropTypes from "prop-types"; -import "./index.css"; - -const levelConfig = { - primary: { - variant: "contained", - color: "primary", - }, - secondary: { - variant: "outlined", - color: "secondary", - }, - tertiary: { - variant: "text", - color: "tertiary", - }, - error: { - variant: "contained", - color: "error", - }, - imagePrimary: { - color: "primary", - variant: "text", - }, - imageSecondary: { - color: "secondary", - variant: "text", - }, - imageTertiary: { - color: "tertiary", - variant: "text", - }, -}; - -/** - * @component - * @param {Object} props - * @param {'primary' | 'secondary' | 'tertiary' | 'error' | 'imagePrimary' | 'imageSecondary' | 'imageTertiary'} props.level - The level of the button - * @param {string} props.type - The type of the button - * @param {string} props.label - The label of the button - * @param {React.ReactNode} props.img - Image for button - * @param {boolean} [props.disabled] - Whether the button is disabled - * @param {function} props.onClick - Function to run when the button is clicked - * @param {Object} props.sx - Styles for the button - * @returns {JSX.Element} - * @example - * // Render an error button - * )} ); diff --git a/Client/src/Components/Inputs/Autocomplete/index.jsx b/Client/src/Components/Inputs/Autocomplete/index.jsx new file mode 100644 index 000000000..5256efccc --- /dev/null +++ b/Client/src/Components/Inputs/Autocomplete/index.jsx @@ -0,0 +1,116 @@ +import { Autocomplete, TextField } from "@mui/material"; +import React from "react"; +import PropTypes from "prop-types"; +import { useTheme } from "@emotion/react"; + +/** + * @example + * + * const options = [ + * { _id: "66d6119ef959cbc681e034f0", name: "Googler" }, + * { _id: "66d6119ef959cbc681e034f0", name: "CNN" }, + * { _id: "66d61a1bf959cbc681e0353f", name: "X Corp." }, + * ]; + * + * + * + */ + +/** + * AutoCompleteField component. + * + * @component + * @param {Object} props - The component props. + * @param {string} props.id - The ID of the autocomplete field. + * @param {string} props.type - The type of the input field (text or number). + * @param {Array} props.options - The options for the autocomplete field. + * @param {string} props.placeholder - The placeholder text for the input field. + * @param {boolean} props.disabled - Indicates if the field is disabled. + * @returns {JSX.Element} The AutoCompleteField component. + */ + +const AutoCompleteField = ({ + id, + type, + options, + placeholder = "Type to search", + disabled, +}) => { + const [value, setValue] = React.useState(); + const [inputValue, setInputValue] = React.useState(""); + const theme = useTheme(); + + return ( + { + setValue(newValue); + }} + inputValue={inputValue} + onInputChange={(event, newInputValue) => { + setInputValue(newInputValue); + }} + options={options} + getOptionLabel={(option) => option.name} + renderInput={(params) => ( + + )} + renderOption={(props, option) => { + const { key, ...optionProps } = props; + return ( +
  • +
    {{option.name}}
    +
  • + ); + }} + slotProps={{ + popper: { + sx: { + "& ul": { p: 0 }, + "& li": { borderRadius: theme.shape.borderRadius }, + }, + }, + paper: { + sx: { + p: 2, + fontSize: 13, + }, + }, + }} + /> + ); +}; + +AutoCompleteField.displayName = "AutoCompleteField"; + +AutoCompleteField.propTypes = { + id: PropTypes.string, + type: PropTypes.oneOf(["text", "number"]), + options: PropTypes.array, + placeholder: PropTypes.string, + disabled: PropTypes.bool, + setWidth: PropTypes.string, +}; + +export default AutoCompleteField; diff --git a/Client/src/Components/Inputs/Image/index.jsx b/Client/src/Components/Inputs/Image/index.jsx index f7bdc9cf0..cdc7d8c7f 100644 --- a/Client/src/Components/Inputs/Image/index.jsx +++ b/Client/src/Components/Inputs/Image/index.jsx @@ -38,12 +38,12 @@ const ImageField = ({ id, src, loading, onChange }) => { border: "dashed", borderRadius: theme.shape.borderRadius, borderColor: isDragging - ? theme.palette.common.main + ? theme.palette.primary.main : theme.palette.border.light, borderWidth: "2px", transition: "0.2s", "&:hover": { - borderColor: theme.palette.common.main, + borderColor: theme.palette.primary.main, backgroundColor: "hsl(215, 87%, 51%, 0.05)", }, }} @@ -96,7 +96,7 @@ const ImageField = ({ id, src, loading, onChange }) => { Click to upload diff --git a/Client/src/Components/Inputs/Select/index.jsx b/Client/src/Components/Inputs/Select/index.jsx index b7146f27a..e30b5d951 100644 --- a/Client/src/Components/Inputs/Select/index.jsx +++ b/Client/src/Components/Inputs/Select/index.jsx @@ -67,6 +67,7 @@ const Select = ({ component="h3" color={theme.palette.text.secondary} fontWeight={500} + fontSize={13} > {label} diff --git a/Client/src/Components/Label/index.jsx b/Client/src/Components/Label/index.jsx index 0799a87d7..886f66fb9 100644 --- a/Client/src/Components/Label/index.jsx +++ b/Client/src/Components/Label/index.jsx @@ -138,6 +138,11 @@ const StatusLabel = ({ status, text, customStyles }) => { bgColor: theme.palette.error.bg, borderColor: theme.palette.error.light, }, + pending: { + dotColor: theme.palette.warning.main, + bgColor: theme.palette.warning.bg, + borderColor: theme.palette.warning.light, + }, "cannot resolve": { dotColor: theme.palette.unresolved.main, bgColor: theme.palette.unresolved.bg, @@ -170,7 +175,7 @@ const StatusLabel = ({ status, text, customStyles }) => { }; StatusLabel.propTypes = { - status: PropTypes.oneOf(["up", "down", "cannot resolve"]), + status: PropTypes.oneOf(["up", "down", "pending", "cannot resolve"]), text: PropTypes.string, customStyles: PropTypes.object, }; diff --git a/Client/src/Components/Link/index.jsx b/Client/src/Components/Link/index.jsx index 025bd0c25..5a055e28e 100644 --- a/Client/src/Components/Link/index.jsx +++ b/Client/src/Components/Link/index.jsx @@ -28,11 +28,11 @@ const Link = ({ level, label, url }) => { sx: { textDecoration: "underline", textDecorationStyle: "dashed", - textDecorationColor: theme.palette.common.main, + textDecorationColor: theme.palette.primary.main, textUnderlineOffset: "1px", ":hover": { color: theme.palette.text.tertiary, - textDecorationColor: theme.palette.common.main, + textDecorationColor: theme.palette.primary.main, backgroundColor: theme.palette.background.fill, }, }, diff --git a/Client/src/Components/Sidebar/index.css b/Client/src/Components/Sidebar/index.css index f8265a2be..b01562ac4 100644 --- a/Client/src/Components/Sidebar/index.css +++ b/Client/src/Components/Sidebar/index.css @@ -75,7 +75,7 @@ aside.collapsed .MuiAvatar-root + .MuiBox-root + .MuiIconButton-root { } aside .MuiListSubheader-root { - transition: all 200ms ease; + transition: padding 200ms ease; } @keyframes fadeIn { diff --git a/Client/src/Components/Sidebar/index.jsx b/Client/src/Components/Sidebar/index.jsx index 2988efb54..c372f8c66 100644 --- a/Client/src/Components/Sidebar/index.jsx +++ b/Client/src/Components/Sidebar/index.jsx @@ -154,7 +154,7 @@ function Sidebar() { color="white" sx={{ position: "relative", - backgroundColor: theme.palette.common.main, + backgroundColor: theme.palette.primary.main, borderRadius: theme.shape.borderRadius, userSelect: "none", }} @@ -598,8 +598,9 @@ function Sidebar() { MenuListProps={{ sx: { p: 2, + "& li": { m: 0 }, "& li:has(.MuiBox-root):hover": { - backgroundColor: theme.palette.background.main, + backgroundColor: "transparent", }, }, }} @@ -620,8 +621,22 @@ function Sidebar() { )} {collapsed && } - dispatch(setMode("light"))}>Light - dispatch(setMode("dark"))}>Dark + { + dispatch(setMode("light")); + closePopup(); + }} + > + Light + + { + dispatch(setMode("dark")); + closePopup(); + }} + > + Dark + { - + > + Save + diff --git a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx b/Client/src/Components/TabPanels/Account/ProfilePanel.jsx index 732919085..885c795b1 100644 --- a/Client/src/Components/TabPanels/Account/ProfilePanel.jsx +++ b/Client/src/Components/TabPanels/Account/ProfilePanel.jsx @@ -1,9 +1,7 @@ import { useTheme } from "@emotion/react"; import { useRef, useState } from "react"; import TabPanel from "@mui/lab/TabPanel"; -import { Box, Divider, Modal, Stack, Typography } from "@mui/material"; -import ButtonSpinner from "../../ButtonSpinner"; -import Button from "../../Button"; +import { Box, Button, Divider, Modal, Stack, Typography } from "@mui/material"; import Avatar from "../../Avatar"; import Field from "../../Inputs/Field"; import ImageField from "../../Inputs/Image"; @@ -20,6 +18,7 @@ import { formatBytes } from "../../../Utils/fileUtils"; import { clearUptimeMonitorState } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { createToast } from "../../../Utils/toastUtils"; import { logger } from "../../../Utils/Logger"; +import LoadingButton from "@mui/lab/LoadingButton"; /** * ProfilePanel component displays a form for editing user profile information @@ -292,19 +291,12 @@ const ProfilePanel = () => { } sx={{ mr: "8px" }} /> - + { /> - + sx={{ px: theme.spacing(12) }} + > + Save + @@ -339,13 +331,8 @@ const ProfilePanel = () => { borderColor: theme.palette.border.light, }} /> - - + + Delete account Note that deleting your account will remove all data from our @@ -353,12 +340,13 @@ const ProfilePanel = () => { + {/* TODO - Update ModalPopup Component with @mui for reusability */} { mt={theme.spacing(5)} justifyContent="flex-end" > - + + loading={isLoading} + > + Delete account + @@ -480,15 +468,19 @@ const ProfilePanel = () => { justifyContent="flex-end" > + diff --git a/Client/src/Components/TabPanels/Account/TeamPanel.jsx b/Client/src/Components/TabPanels/Account/TeamPanel.jsx index 9c63bd1c2..9809ac710 100644 --- a/Client/src/Components/TabPanels/Account/TeamPanel.jsx +++ b/Client/src/Components/TabPanels/Account/TeamPanel.jsx @@ -1,27 +1,15 @@ import { useTheme } from "@emotion/react"; import TabPanel from "@mui/lab/TabPanel"; -import { - Box, - ButtonGroup, - Divider, - IconButton, - Modal, - Stack, - TextField, - Typography, -} from "@mui/material"; -import ButtonSpinner from "../../ButtonSpinner"; -import Button from "../../Button"; +import { Button, ButtonGroup, Modal, Stack, Typography } from "@mui/material"; import { useEffect, useState } from "react"; -import EditSvg from "../../../assets/icons/edit.svg?react"; import Field from "../../Inputs/Field"; import { credentials } from "../../../Validation/validation"; import { networkService } from "../../../main"; import { createToast } from "../../../Utils/toastUtils"; import { useSelector } from "react-redux"; import BasicTable from "../../BasicTable"; -import Remove from "../../../assets/icons/trash-bin.svg?react"; import Select from "../../Inputs/Select"; +import LoadingButton from "@mui/lab/LoadingButton"; /** * TeamPanel component manages the organization and team members, @@ -54,6 +42,7 @@ const TeamPanel = () => { const [members, setMembers] = useState([]); const [filter, setFilter] = useState("all"); const [errors, setErrors] = useState({}); + const [isSendingInvite, setIsSendingInvite] = useState(false); useEffect(() => { const fetchTeam = async () => { @@ -173,6 +162,7 @@ const TeamPanel = () => { }; const handleInviteMember = async () => { + setIsSendingInvite(true); if (!toInvite.role.includes("user") || !toInvite.role.includes("admin")) setToInvite((prev) => ({ ...prev, role: ["user"] })); @@ -185,24 +175,28 @@ const TeamPanel = () => { if (error) { setErrors((prev) => ({ ...prev, email: error.details[0].message })); - } else - try { - await networkService.requestInvitationToken( - authToken, - toInvite.email, - toInvite.role - ); + return; + } - closeInviteModal(); - createToast({ - body: "Member invited. They will receive an email with details on how to create their account.", - }); - } catch (error) { - createToast({ - body: error.message || "Unknown error.", - }); - } + try { + await networkService.requestInvitationToken( + authToken, + toInvite.email, + toInvite.role + ); + closeInviteModal(); + createToast({ + body: "Member invited. They will receive an email with details on how to create their account.", + }); + } catch (error) { + createToast({ + body: error.message || "Unknown error.", + }); + } finally { + setIsSendingInvite(false); + } }; + const closeInviteModal = () => { setIsOpen(false); setToInvite({ email: "", role: ["0"] }); @@ -283,48 +277,38 @@ const TeamPanel = () => { gap={theme.spacing(6)} sx={{ fontSize: 14 }} > - + - Didn't receive the email?{" "} { diff --git a/Client/src/Pages/Auth/ForgotPassword.jsx b/Client/src/Pages/Auth/ForgotPassword.jsx index f174b2322..338da645c 100644 --- a/Client/src/Pages/Auth/ForgotPassword.jsx +++ b/Client/src/Pages/Auth/ForgotPassword.jsx @@ -7,10 +7,10 @@ import { useEffect, useState } from "react"; import { credentials } from "../../Validation/validation"; import { useNavigate } from "react-router-dom"; import Field from "../../Components/Inputs/Field"; -import ButtonSpinner from "../../Components/ButtonSpinner"; import Logo from "../../assets/icons/bwu-icon.svg?react"; import Key from "../../assets/icons/key.svg?react"; import background from "../../assets/Images/background_pattern_decorative.png"; +import LoadingButton from "@mui/lab/LoadingButton"; import "./index.css"; const ForgotPassword = () => { @@ -92,7 +92,7 @@ const ForgotPassword = () => { overflow="hidden" sx={{ "& h1": { - color: theme.palette.common.main, + color: theme.palette.primary.main, fontWeight: 600, fontSize: 24, }, @@ -166,18 +166,19 @@ const ForgotPassword = () => { onChange={handleChange} error={errors.email} /> - + > + Send instructions + @@ -185,7 +186,7 @@ const ForgotPassword = () => { Go back to — { @@ -151,27 +155,29 @@ const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => { @@ -219,6 +225,7 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => { <> @@ -243,39 +250,49 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => { - + Forgot password? { overflow="hidden" sx={{ "& h1": { - color: theme.palette.common.main, + color: theme.palette.primary.main, fontWeight: 600, fontSize: 30, }, @@ -491,7 +508,7 @@ const Login = () => { { navigate("/register"); diff --git a/Client/src/Pages/Auth/NewPasswordConfirmed.jsx b/Client/src/Pages/Auth/NewPasswordConfirmed.jsx index 89e8fd110..7be6d325d 100644 --- a/Client/src/Pages/Auth/NewPasswordConfirmed.jsx +++ b/Client/src/Pages/Auth/NewPasswordConfirmed.jsx @@ -1,10 +1,9 @@ -import { Box, Stack, Typography } from "@mui/material"; +import { Box, Button, Stack, Typography } from "@mui/material"; import { useTheme } from "@emotion/react"; import { useNavigate } from "react-router"; import { useDispatch } from "react-redux"; import { clearAuthState } from "../../Features/Auth/authSlice"; import { clearUptimeMonitorState } from "../../Features/UptimeMonitors/uptimeMonitorsSlice"; -import Button from "../../Components/Button"; import background from "../../assets/Images/background_pattern_decorative.png"; import ConfirmIcon from "../../assets/icons/confirm-icon.svg?react"; import Logo from "../../assets/icons/bwu-icon.svg?react"; @@ -27,7 +26,7 @@ const NewPasswordConfirmed = () => { overflow="hidden" sx={{ "& h1": { - color: theme.palette.common.main, + color: theme.palette.primary.main, fontWeight: 600, fontSize: 22, }, @@ -85,21 +84,23 @@ const NewPasswordConfirmed = () => { Go back to — { @@ -180,26 +183,29 @@ const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => { @@ -270,26 +276,29 @@ const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => { @@ -443,26 +452,29 @@ const StepThree = ({ form, errors, onSubmit, onChange, onBack }) => { @@ -644,7 +656,7 @@ const Register = ({ isSuperAdmin }) => { overflow="hidden" sx={{ "& h1": { - color: theme.palette.common.main, + color: theme.palette.primary.main, fontWeight: 600, fontSize: 30, }, @@ -731,7 +743,7 @@ const Register = ({ isSuperAdmin }) => { onClick={() => { navigate("/login"); }} - sx={{ userSelect: "none", color: theme.palette.common.main }} + sx={{ userSelect: "none", color: theme.palette.primary.main }} > Log In diff --git a/Client/src/Pages/Auth/SetNewPassword.jsx b/Client/src/Pages/Auth/SetNewPassword.jsx index ca54e6fc8..a01e9bd51 100644 --- a/Client/src/Pages/Auth/SetNewPassword.jsx +++ b/Client/src/Pages/Auth/SetNewPassword.jsx @@ -8,11 +8,11 @@ import { useState } from "react"; import { credentials } from "../../Validation/validation"; import { useNavigate } from "react-router-dom"; import Check from "../../Components/Check/Check"; -import ButtonSpinner from "../../Components/ButtonSpinner"; import Field from "../../Components/Inputs/Field"; import LockIcon from "../../assets/icons/lock-button-icon.svg?react"; import background from "../../assets/Images/background_pattern_decorative.png"; import Logo from "../../assets/icons/bwu-icon.svg?react"; +import LoadingButton from "@mui/lab/LoadingButton"; import "./index.css"; const SetNewPassword = () => { @@ -109,7 +109,7 @@ const SetNewPassword = () => { overflow="hidden" sx={{ "& h1": { - color: theme.palette.common.main, + color: theme.palette.primary.main, fontWeight: 600, fontSize: 24, }, @@ -266,21 +266,23 @@ const SetNewPassword = () => { /> - + > + Reset password + Go back to — navigate("/login")} sx={{ userSelect: "none" }} diff --git a/Client/src/Pages/Incidents/IncidentTable/index.jsx b/Client/src/Pages/Incidents/IncidentTable/index.jsx index aa80b35ce..d10c79c68 100644 --- a/Client/src/Pages/Incidents/IncidentTable/index.jsx +++ b/Client/src/Pages/Incidents/IncidentTable/index.jsx @@ -15,14 +15,12 @@ import { import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded"; import ArrowForwardRoundedIcon from "@mui/icons-material/ArrowForwardRounded"; - import { useState, useEffect } from "react"; import { useSelector } from "react-redux"; import { networkService } from "../../../main"; import { StatusLabel } from "../../../Components/Label"; import { logger } from "../../../Utils/Logger"; import { useTheme } from "@emotion/react"; - const IncidentTable = ({ monitors, selectedMonitor, filter }) => { const theme = useTheme(); const { authToken, user } = useSelector((state) => state.auth); diff --git a/Client/src/Pages/Incidents/index.jsx b/Client/src/Pages/Incidents/index.jsx index 75e8fb174..1fd91c10a 100644 --- a/Client/src/Pages/Incidents/index.jsx +++ b/Client/src/Pages/Incidents/index.jsx @@ -1,38 +1,12 @@ import { useState, useEffect } from "react"; import { useSelector } from "react-redux"; -import { ButtonGroup, Stack, Skeleton, Typography } from "@mui/material"; -import Button from "../../Components/Button"; +import { ButtonGroup, Stack, Typography, Button } from "@mui/material"; import { networkService } from "../../main"; import { useTheme } from "@emotion/react"; import Select from "../../Components/Inputs/Select"; import IncidentTable from "./IncidentTable"; import "./index.css"; - -/** - * Renders a skeleton layout. - * - * @returns {JSX.Element} - */ -const SkeletonLayout = () => { - const theme = useTheme(); - - return ( - <> - - - - - - - - - ); -}; +import SkeletonLayout from "./skeleton"; const Incidents = () => { const theme = useTheme(); @@ -55,11 +29,13 @@ const Incidents = () => { null, null, null, + null, + null, null ); // Reduce to a lookup object for 0(1) lookup - if (res.data && res.data.data.length > 0) { - const monitorLookup = res.data.data.reduce((acc, monitor) => { + if (res?.data?.data?.monitors?.length > 0) { + const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => { acc[monitor._id] = monitor; return acc; }, {}); @@ -78,11 +54,7 @@ const Incidents = () => { }; return ( - + {loading ? ( ) : ( @@ -114,38 +86,26 @@ const Incidents = () => { }} > { + const theme = useTheme(); + + return ( + <> + + + + + + + + + ); +}; + +export default SkeletonLayout; diff --git a/Client/src/Pages/Integrations/index.jsx b/Client/src/Pages/Integrations/index.jsx index 0e3bd71b9..d292d1aa2 100644 --- a/Client/src/Pages/Integrations/index.jsx +++ b/Client/src/Pages/Integrations/index.jsx @@ -1,6 +1,5 @@ import PropTypes from "prop-types"; -import { Stack, Typography, Grid } from "@mui/material"; -import Button from "../../Components/Button"; +import { Stack, Typography, Grid, Button } from "@mui/material"; import { useTheme } from "@emotion/react"; import Discord from "../../assets/icons/discord-icon.svg?react"; import Slack from "../../assets/icons/slack-icon.svg?react"; @@ -47,12 +46,14 @@ const IntegrationsComponent = ({ icon, header, info, onClick }) => { ); diff --git a/Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx b/Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx index 0c6a16d5e..43102ac21 100644 --- a/Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx +++ b/Client/src/Pages/Maintenance/CreateMaintenanceWindow/index.jsx @@ -1,7 +1,6 @@ -import { Box, Stack, Typography } from "@mui/material"; +import { Box, Button, Stack, Typography } from "@mui/material"; import "./index.css"; import { useState } from "react"; -import Button from "../../../Components/Button"; import Back from "../../../assets/icons/left-arrow-long.svg?react"; import Select from "../../../Components/Inputs/Select"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; @@ -215,7 +214,7 @@ const CreateNewMaintenanceWindow = () => { sx={{ width: "fit-content", fontSize: "var(--env-var-font-size-small)", - borderBottom: `1px dashed ${theme.palette.common.main}`, + borderBottom: `1px dashed ${theme.palette.primary.main}`, paddingBottom: "4px", }} > @@ -230,18 +229,17 @@ const CreateNewMaintenanceWindow = () => {
    { +
    diff --git a/Client/src/Pages/Monitors/Configure/index.jsx b/Client/src/Pages/Monitors/Configure/index.jsx index 9a90c5512..1ee171034 100644 --- a/Client/src/Pages/Monitors/Configure/index.jsx +++ b/Client/src/Pages/Monitors/Configure/index.jsx @@ -2,7 +2,7 @@ import { useNavigate, useParams } from "react-router"; import { useTheme } from "@emotion/react"; import { useDispatch, useSelector } from "react-redux"; import { useEffect, useState } from "react"; -import { Box, Modal, Stack, Typography } from "@mui/material"; +import { Box, Button, Modal, Stack, Typography } from "@mui/material"; import { monitorValidation } from "../../../Validation/validation"; import { createToast } from "../../../Utils/toastUtils"; import { logger } from "../../../Utils/Logger"; @@ -14,16 +14,17 @@ import { getUptimeMonitorsByTeamId, deleteUptimeMonitor, } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; -import Button from "../../../Components/Button"; import Field from "../../../Components/Inputs/Field"; import PauseCircleOutlineIcon from "@mui/icons-material/PauseCircleOutline"; +import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded"; import Select from "../../../Components/Inputs/Select"; import Checkbox from "../../../Components/Inputs/Checkbox"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import PulseDot from "../../../Components/Animated/PulseDot"; -import "./index.css"; import SkeletonLayout from "./skeleton"; -import ButtonSpinner from "../../../Components/ButtonSpinner"; +import LoadingButton from "@mui/lab/LoadingButton"; +import "./index.css"; + /** * Parses a URL string and returns a URL object. * @@ -52,7 +53,6 @@ const Configure = () => { const [monitor, setMonitor] = useState({}); const [errors, setErrors] = useState({}); const { monitorId } = useParams(); - const idMap = { "monitor-url": "url", "monitor-name": "name", @@ -189,6 +189,18 @@ const Configure = () => { const parsedUrl = parseUrl(monitor?.url); const protocol = parsedUrl?.protocol?.replace(":", "") || ""; + const statusColor = { + true: theme.palette.success.main, + false: theme.palette.error.main, + undefined: theme.palette.warning.main, + }; + + const statusMsg = { + true: "Your site is up.", + false: "Your site is down.", + undefined: "Pending...", + }; + return ( {Object.keys(monitor).length === 0 ? ( @@ -210,13 +222,7 @@ const Configure = () => { flex={1} > - + {parsedUrl?.host ? ( { - Your site is {monitor?.status ? "up" : "down"}. + {statusMsg[monitor?.status ?? undefined]} { ml: "auto", }} > - } + - + {monitor?.isActive ? ( + <> + + Pause + + ) : ( + <> + + Resume + + )} + + setIsOpen(true)} - /> + > + Remove + @@ -381,13 +392,15 @@ const Configure = () => { - + > + Save + @@ -440,11 +453,20 @@ const Configure = () => { justifyContent="flex-end" > + + Delete + diff --git a/Client/src/Pages/Monitors/CreateMonitor/index.jsx b/Client/src/Pages/Monitors/CreateMonitor/index.jsx index e2944b659..408c5788d 100644 --- a/Client/src/Pages/Monitors/CreateMonitor/index.jsx +++ b/Client/src/Pages/Monitors/CreateMonitor/index.jsx @@ -1,5 +1,5 @@ import { useState, useEffect } from "react"; -import { Box, ButtonGroup, Stack, Typography } from "@mui/material"; +import { Box, Button, ButtonGroup, Stack, Typography } from "@mui/material"; import { useSelector, useDispatch } from "react-redux"; import { monitorValidation } from "../../../Validation/validation"; import { createUptimeMonitor } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; @@ -9,7 +9,6 @@ import { createToast } from "../../../Utils/toastUtils"; import { logger } from "../../../Utils/Logger"; import { ConfigBox } from "../styled"; import Radio from "../../../Components/Inputs/Radio"; -import Button from "../../../Components/Button"; import Field from "../../../Components/Inputs/Field"; import Select from "../../../Components/Inputs/Select"; import Checkbox from "../../../Components/Inputs/Checkbox"; @@ -44,16 +43,16 @@ const CreateMonitor = () => { const [errors, setErrors] = useState({}); useEffect(() => { - if(monitorId){ + if (monitorId) { const data = monitors.find((monitor) => monitor._id === monitorId); if (!data) { console.error("Error fetching monitor of id: " + monitorId); - navigate("/not-found", {replace: true}); + navigate("/not-found", { replace: true }); } - const {name, ...rest} = data; //data.name is read-only - if(rest.type === 'http'){ - const url = new URL(rest.url) - rest.url = url.host + const { name, ...rest } = data; //data.name is read-only + if (rest.type === "http") { + const url = new URL(rest.url); + rest.url = url.host; } rest.name = `${name} (Clone)`; rest.interval /= MS_PER_MINUTE; @@ -254,29 +253,19 @@ const CreateMonitor = () => { {monitor.type === "http" ? ( ) : ( "" @@ -376,12 +365,13 @@ const CreateMonitor = () => { diff --git a/Client/src/Pages/Monitors/Details/Charts/index.jsx b/Client/src/Pages/Monitors/Details/Charts/index.jsx new file mode 100644 index 000000000..cb0afb55b --- /dev/null +++ b/Client/src/Pages/Monitors/Details/Charts/index.jsx @@ -0,0 +1,283 @@ +import { useTheme } from "@emotion/react"; +import { + BarChart, + Bar, + XAxis, + ResponsiveContainer, + Cell, + RadialBarChart, + RadialBar, +} from "recharts"; +import { formatDate } from "../../../../Utils/timeUtils"; +import { memo, useMemo, useState } from "react"; + +const CustomLabels = ({ + x, + width, + height, + firstDataPoint, + lastDataPoint, + type, +}) => { + let options = { + month: "short", + year: undefined, + hour: undefined, + minute: undefined, + }; + if (type === "day") delete options.hour; + + return ( + <> + + {formatDate(new Date(firstDataPoint.time), options)} + + + {formatDate(new Date(lastDataPoint.time), options)} + + + ); +}; + +export const UpBarChart = memo(({ data, type, onBarHover }) => { + const theme = useTheme(); + + const [chartHovered, setChartHovered] = useState(false); + const [hoveredBarIndex, setHoveredBarIndex] = useState(null); + + const getColorRange = (uptime) => { + return uptime > 80 + ? { main: theme.palette.success.main, light: theme.palette.success.light } + : uptime > 50 + ? { main: theme.palette.warning.main, light: theme.palette.warning.light } + : { main: theme.palette.error.text, light: theme.palette.error.light }; + }; + + // TODO - REMOVE THIS LATER + const reversedData = useMemo(() => [...data].reverse(), [data]); + + return ( + + { + setChartHovered(true); + onBarHover({ time: null, totalChecks: 0, uptimePercentage: 0 }); + }} + onMouseLeave={() => { + setChartHovered(false); + setHoveredBarIndex(null); + onBarHover(null); + }} + > + + } + /> + + {reversedData.map((entry, index) => { + let { main, light } = getColorRange(entry.uptimePercentage); + return ( + { + setHoveredBarIndex(index); + onBarHover(entry); + }} + onMouseLeave={() => { + setHoveredBarIndex(null); + onBarHover({ + time: null, + totalChecks: 0, + uptimePercentage: 0, + }); + }} + /> + ); + })} + + + + ); +}); + +export const DownBarChart = memo(({ data, type, onBarHover }) => { + const theme = useTheme(); + + const [chartHovered, setChartHovered] = useState(false); + const [hoveredBarIndex, setHoveredBarIndex] = useState(null); + + // TODO - REMOVE THIS LATER + const reversedData = useMemo(() => [...data].reverse(), [data]); + + return ( + + { + setChartHovered(true); + onBarHover({ time: null, totalIncidents: 0 }); + }} + onMouseLeave={() => { + setChartHovered(false); + setHoveredBarIndex(null); + onBarHover(null); + }} + > + + } + /> + + {reversedData.map((entry, index) => ( + { + setHoveredBarIndex(index); + onBarHover(entry); + }} + onMouseLeave={() => { + setHoveredBarIndex(null); + onBarHover({ time: null, totalIncidents: 0 }); + }} + /> + ))} + + + + ); +}); + +export const ResponseGaugeChart = ({ data }) => { + const theme = useTheme(); + + let max = 1000; // max ms + + const memoizedData = useMemo( + () => [{ response: max, fill: "transparent", background: false }, ...data], + [data[0].response] + ); + + let responseTime = Math.floor(memoizedData[1].response); + let responseProps = + responseTime <= 200 + ? { + category: "Excellent", + main: theme.palette.success.main, + bg: theme.palette.success.bg, + } + : responseTime <= 500 + ? { + category: "Fair", + main: theme.palette.success.main, + bg: theme.palette.success.bg, + } + : responseTime <= 600 + ? { + category: "Acceptable", + main: theme.palette.warning.main, + bg: theme.palette.warning.bg, + } + : { + category: "Poor", + main: theme.palette.error.text, + bg: theme.palette.error.bg, + }; + + return ( + + + + low + + + high + + + {responseProps.category} + + + {responseTime}{" "} + ms + + + + + + + + ); +}; diff --git a/Client/src/Pages/Monitors/Details/index.css b/Client/src/Pages/Monitors/Details/index.css index 59ffc5d85..8b1378917 100644 --- a/Client/src/Pages/Monitors/Details/index.css +++ b/Client/src/Pages/Monitors/Details/index.css @@ -1,18 +1 @@ -.monitor-details h1.MuiTypography-root { - font-size: var(--env-var-font-size-large-plus); - font-weight: 600; -} -.monitor-details h2.MuiTypography-root { - font-size: var(--env-var-font-size-large); -} -.monitor-details h2.MuiTypography-root { - font-weight: 600; -} -.monitor-details button.MuiButtonBase-root { - height: var(--env-var-height-2); - line-height: 1; -} -.monitor-details p.MuiTypography-root, -.monitor-details p.MuiTypography-root span.MuiTypography-root { - font-size: var(--env-var-font-size-small-plus); -} + diff --git a/Client/src/Pages/Monitors/Details/index.jsx b/Client/src/Pages/Monitors/Details/index.jsx index 1506cd86f..e31de38d7 100644 --- a/Client/src/Pages/Monitors/Details/index.jsx +++ b/Client/src/Pages/Monitors/Details/index.jsx @@ -1,140 +1,41 @@ import PropTypes from "prop-types"; import { useEffect, useState, useCallback } from "react"; -import { Box, Skeleton, Stack, Typography, useTheme } from "@mui/material"; +import { + Box, + Button, + Popover, + Stack, + Tooltip, + Typography, + useTheme, +} from "@mui/material"; import { useSelector } from "react-redux"; import { useNavigate, useParams } from "react-router-dom"; import { networkService } from "../../../main"; import { logger } from "../../../Utils/Logger"; import { + formatDate, formatDuration, formatDurationRounded, + formatDurationSplit, } from "../../../Utils/timeUtils"; import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart"; import ButtonGroup from "@mui/material/ButtonGroup"; -import Button from "../../../Components/Button"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; +import CertificateIcon from "../../../assets/icons/certificate.svg?react"; +import UptimeIcon from "../../../assets/icons/uptime-icon.svg?react"; +import ResponseTimeIcon from "../../../assets/icons/response-time-icon.svg?react"; +import AverageResponseIcon from "../../../assets/icons/average-response-icon.svg?react"; +import IncidentsIcon from "../../../assets/icons/incidents.svg?react"; +import HistoryIcon from "../../../assets/icons/history-icon.svg?react"; import PaginationTable from "./PaginationTable"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import PulseDot from "../../../Components/Animated/PulseDot"; +import { StatBox, ChartBox, IconBox } from "./styled"; +import { DownBarChart, ResponseGaugeChart, UpBarChart } from "./Charts"; +import SkeletonLayout from "./skeleton"; import "./index.css"; -const StatBox = ({ title, value }) => { - const theme = useTheme(); - return ( - - - {title} - - - {value} - - - ); -}; - -StatBox.propTypes = { - title: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), - value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), -}; - -/** - * Renders a skeleton layout. - * - * @returns {JSX.Element} - */ -const SkeletonLayout = () => { - const theme = useTheme(); - - return ( - <> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); -}; - /** * Details page component displaying monitor details and related information. * @component @@ -148,6 +49,14 @@ const DetailsPage = ({ isAdmin }) => { const [certificateExpiry, setCertificateExpiry] = useState("N/A"); const navigate = useNavigate(); + const [anchorEl, setAnchorEl] = useState(null); + const openCertificate = (event) => { + setAnchorEl(event.currentTarget); + }; + const closeCertificate = () => { + setAnchorEl(null); + }; + const fetchMonitor = useCallback(async () => { try { const res = await networkService.getStatsByMonitorId( @@ -180,7 +89,16 @@ const DetailsPage = ({ isAdmin }) => { authToken, monitorId ); - setCertificateExpiry(res?.data?.data?.certificateDate ?? "N/A"); + + let [month, day, year] = res?.data?.data?.certificateDate.split("/"); + const date = new Date(year, month - 1, day); + + setCertificateExpiry( + formatDate(date, { + hour: undefined, + minute: undefined, + }) ?? "N/A" + ); } catch (error) { console.error(error); } @@ -188,7 +106,33 @@ const DetailsPage = ({ isAdmin }) => { fetchCertificate(); }, [authToken, monitorId, monitor]); + const splitDuration = (duration) => { + const { time, format } = formatDurationSplit(duration); + return ( + <> + {time} + {format} + + ); + }; + let loading = Object.keys(monitor).length === 0; + + const [hoveredUptimeData, setHoveredUptimeData] = useState(null); + const [hoveredIncidentsData, setHoveredIncidentsData] = useState(null); + + const statusColor = { + true: theme.palette.success.main, + false: theme.palette.error.main, + undefined: theme.palette.warning.main, + }; + + const statusMsg = { + true: "Your site is up.", + false: "Your site is down.", + undefined: "Pending...", + }; + return ( {loading ? ( @@ -201,187 +145,378 @@ const DetailsPage = ({ isAdmin }) => { { name: "details", path: `/monitors/${monitorId}` }, ]} /> - + - - {monitor.url?.replace(/^https?:\/\//, "") || "..."} + {monitor.name} - - - Your site is {monitor?.status ? "up" : "down"}. - {" "} - Checking every {formatDurationRounded(monitor?.interval)}. - + + + + + + {monitor.url?.replace(/^https?:\/\//, "") || "..."} + + + Checking every {formatDurationRounded(monitor?.interval)}. + + - {isAdmin && ( - + )} + - + - - - - - - Avg. Response Time{" "} - (24-hr) - + sx={ + monitor?.status === undefined + ? { + backgroundColor: theme.palette.warning.light, + borderColor: theme.palette.warning.border, + "& h2": { color: theme.palette.warning.main }, + } + : monitor?.status + ? { + backgroundColor: theme.palette.success.bg, + borderColor: theme.palette.success.light, + "& h2": { color: theme.palette.success.main }, + } + : { + backgroundColor: theme.palette.error.bg, + borderColor: theme.palette.error.light, + "& h2": { color: theme.palette.error.main }, + } } - value={parseFloat(monitor?.avgResponseTime24hours) - .toFixed(2) - .replace(/\.?0+$/, "")} - /> - - Uptime (24-hr) - - } - value={`${parseFloat(monitor?.uptime24Hours) - .toFixed(2) - .replace(/\.?0+$/, "")}%`} - /> - - Uptime (30-day) - - } - value={`${parseFloat(monitor?.uptime30Days) - .toFixed(2) - .replace(/\.?0+$/, "")}%`} - /> + > + active for + + {splitDuration(monitor?.uptimeDuration)} + + + + last check + + {splitDuration(monitor?.lastChecked)} + ago + + + + last response time + + {monitor?.latestResponseTime} + ms + + - - Response Times + + Showing statistics for past{" "} + {dateRange === "day" + ? "24 hours" + : dateRange === "week" + ? "7 days" + : "30 days"} + . - + + + + + + + + + + + + Uptime + + + + Total Checks + + {hoveredUptimeData !== null + ? hoveredUptimeData.totalChecks + : monitor?.periodTotalChecks} + + {hoveredUptimeData !== null && + hoveredUptimeData.time !== null && ( + + {formatDate(new Date(hoveredUptimeData.time), { + month: "short", + year: undefined, + minute: undefined, + hour: dateRange === "day" ? "numeric" : undefined, + })} + + )} + + + Uptime Percentage + + {hoveredUptimeData !== null + ? Math.floor( + hoveredUptimeData.uptimePercentage * 10 + ) / 10 + : Math.floor(monitor?.periodUptime * 10) / 10} + % + + + + + + + + + + + Incidents + + + Total Incidents + + {hoveredIncidentsData !== null + ? hoveredIncidentsData.totalIncidents + : monitor?.periodIncidents} + + {hoveredIncidentsData !== null && + hoveredIncidentsData.time !== null && ( + + {formatDate(new Date(hoveredIncidentsData.time), { + month: "short", + year: undefined, + minute: undefined, + hour: dateRange === "day" ? "numeric" : undefined, + })} + + )} + + + + + + + + + + Average Response Time + + + + + - + + + + + ); +}; + +TablePaginationActions.propTypes = { + count: PropTypes.number.isRequired, + page: PropTypes.number.isRequired, + rowsPerPage: PropTypes.number.isRequired, + onPageChange: PropTypes.func.isRequired, +}; + +const MonitorTable = ({ isAdmin }) => { + const theme = useTheme(); + const navigate = useNavigate(); + const dispatch = useDispatch(); + + const { rowsPerPage } = useSelector((state) => state.ui.monitors); + const [page, setPage] = useState(0); + const [monitors, setMonitors] = useState([]); + const [monitorCount, setMonitorCount] = useState(0); + const authState = useSelector((state) => state.auth); + const [updateTrigger, setUpdateTrigger] = useState(false); + + const handleActionMenuDelete = () => { + setUpdateTrigger((prev) => !prev); + }; + + const handleChangePage = (event, newPage) => { + setPage(newPage); + }; + + const handleChangeRowsPerPage = (event) => { + dispatch( + setRowsPerPage({ + value: parseInt(event.target.value, 10), + table: "monitors", + }) + ); + setPage(0); + }; + + useEffect(() => { + const fetchPage = async () => { + try { + const { authToken } = authState; + const user = jwtDecode(authToken); + const res = await networkService.getMonitorsByTeamId( + authToken, + user.teamId, + 25, + ["http", "ping"], + null, + "desc", + true, + page, + rowsPerPage + ); + setMonitors(res?.data?.data?.monitors ?? []); + setMonitorCount(res?.data?.data?.monitorCount ?? 0); + } catch (error) { + logger.error(error); + } + }; + fetchPage(); + }, [updateTrigger, authState, page, rowsPerPage]); + + /** + * Helper function to calculate the range of displayed rows. + * @returns {string} + */ + const getRange = () => { + let start = page * rowsPerPage + 1; + let end = Math.min(page * rowsPerPage + rowsPerPage, monitorCount); + return `${start} - ${end}`; + }; + + return ( + <> + +
    + + + Host + + {" "} + + Status + + + + + + Response Time + Type + Actions + + + + {monitors.map((monitor) => { + let uptimePercentage = ""; + let percentageColor = theme.palette.percentage.uptimeExcellent; + + // Determine uptime percentage and color based on the monitor's uptimePercentage value + if (monitor.uptimePercentage !== undefined) { + uptimePercentage = + monitor.uptimePercentage === 0 + ? "0" + : (monitor.uptimePercentage * 100).toFixed(2); + + percentageColor = + monitor.uptimePercentage < 0.25 + ? theme.palette.percentage.uptimePoor + : monitor.uptimePercentage < 0.5 + ? theme.palette.percentage.uptimeFair + : monitor.uptimePercentage < 0.75 + ? theme.palette.percentage.uptimeGood + : theme.palette.percentage.uptimeExcellent; + } + + const params = { + url: monitor.url, + title: monitor.name, + percentage: uptimePercentage, + percentageColor, + status: + monitor.status === undefined + ? "pending" + : monitor.status === true + ? "up" + : "down", + }; + + return ( + { + navigate(`/monitors/${monitor._id}`); + }} + > + + + + + + + + + + + + {monitor.type} + + + + + + + ); + })} + +
    +
    + + + Showing {getRange()} of {monitorCount} monitor(s) + + + `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}` + } + slotProps={{ + select: { + MenuProps: { + keepMounted: true, + PaperProps: { + className: "pagination-dropdown", + sx: { + mt: 0, + mb: theme.spacing(2), + }, + }, + transformOrigin: { vertical: "bottom", horizontal: "left" }, + anchorOrigin: { vertical: "top", horizontal: "left" }, + sx: { mt: theme.spacing(-2) }, + }, + inputProps: { id: "pagination-dropdown" }, + IconComponent: SelectorVertical, + sx: { + ml: theme.spacing(4), + mr: theme.spacing(12), + minWidth: theme.spacing(20), + textAlign: "left", + "&.Mui-focused > div": { + backgroundColor: theme.palette.background.main, + }, + }, + }, + }} + sx={{ + mt: theme.spacing(6), + color: theme.palette.text.secondary, + "& svg path": { + stroke: theme.palette.text.tertiary, + strokeWidth: 1.3, + }, + "& .MuiSelect-select": { + border: 1, + borderColor: theme.palette.border.light, + borderRadius: theme.shape.borderRadius, + }, + }} + /> + + + ); +}; + +MonitorTable.propTypes = { + isAdmin: PropTypes.bool, +}; + +export default MonitorTable; diff --git a/Client/src/Pages/Monitors/Home/StatusBox.jsx b/Client/src/Pages/Monitors/Home/StatusBox.jsx index a7c56d75a..ece8cde16 100644 --- a/Client/src/Pages/Monitors/Home/StatusBox.jsx +++ b/Client/src/Pages/Monitors/Home/StatusBox.jsx @@ -2,7 +2,7 @@ import PropTypes from "prop-types"; import { useTheme } from "@emotion/react"; import { Box, Stack, Typography } from "@mui/material"; import Arrow from "../../../assets/icons/top-right-arrow.svg?react"; -import background from "../../../assets/Images/background-grid.svg"; +import Background from "../../../assets/Images/background-grid.svg?react"; import ClockSnooze from "../../../assets/icons/clock-snooze.svg?react"; const StatusBox = ({ title, value }) => { @@ -48,26 +48,27 @@ const StatusBox = ({ title, value }) => { borderColor={theme.palette.border.light} borderRadius={theme.shape.borderRadius} backgroundColor={theme.palette.background.main} - px={theme.spacing(12)} - py={theme.spacing(8)} + p={theme.spacing(8)} overflow="hidden" sx={{ "&:hover": { backgroundColor: theme.palette.background.accent, }, - "&:after": { - position: "absolute", - content: `""`, - backgroundImage: `url(${background})`, - width: "400px", - height: "200px", - top: "-10%", - left: "5%", - zIndex: 10000, - pointerEvents: "none", - }, }} > + + + { +const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { const [anchorEl, setAnchorEl] = useState(null); const [actions, setActions] = useState({}); const [isOpen, setIsOpen] = useState(false); @@ -37,6 +37,7 @@ const ActionsMenu = ({ monitor, isAdmin }) => { if (action.meta.requestStatus === "fulfilled") { setIsOpen(false); // close modal dispatch(getUptimeMonitorsByTeamId(authState.authToken)); + updateCallback(); createToast({ body: "Monitor deleted successfully." }); } else { createToast({ body: "Failed to delete monitor." }); @@ -93,17 +94,8 @@ const ActionsMenu = ({ monitor, isAdmin }) => { slotProps={{ paper: { sx: { - "& ul": { - p: theme.spacing(2.5), - minWidth: "100px", - }, - "& li": { - color: theme.palette.text.secondary, - fontSize: 13, - px: theme.spacing(4), - py: theme.spacing(2.5), - borderRadius: theme.shape.borderRadius, - }, + "& ul": { p: theme.spacing(2.5) }, + "& li": { m: 0 }, "& li:last-of-type": { color: theme.palette.error.text, }, @@ -206,21 +198,25 @@ const ActionsMenu = ({ monitor, isAdmin }) => { justifyContent="flex-end" > @@ -235,6 +231,7 @@ ActionsMenu.propTypes = { type: PropTypes.string, }).isRequired, isAdmin: PropTypes.bool, + updateCallback: PropTypes.func, }; export default ActionsMenu; diff --git a/Client/src/Pages/Monitors/Home/fallback.jsx b/Client/src/Pages/Monitors/Home/fallback.jsx index c5d41ee48..270f23f29 100644 --- a/Client/src/Pages/Monitors/Home/fallback.jsx +++ b/Client/src/Pages/Monitors/Home/fallback.jsx @@ -1,6 +1,5 @@ -import { Stack, Typography } from "@mui/material"; +import { Button, Stack, Typography } from "@mui/material"; import { useTheme } from "@emotion/react"; -import Button from "../../../Components/Button"; import { useNavigate } from "react-router-dom"; import PropTypes from "prop-types"; @@ -25,13 +24,15 @@ const Fallback = ({ isAdmin }) => { {isAdmin && ( )} ); diff --git a/Client/src/Pages/Monitors/Home/host.jsx b/Client/src/Pages/Monitors/Home/host.jsx index d450a53f4..9e6a71a05 100644 --- a/Client/src/Pages/Monitors/Home/host.jsx +++ b/Client/src/Pages/Monitors/Home/host.jsx @@ -53,7 +53,8 @@ Host.propTypes = { params: PropTypes.shape({ title: PropTypes.string, percentageColor: PropTypes.string, - percentage: PropTypes.number, + percentage: PropTypes.string, + url: PropTypes.string, }).isRequired, }; diff --git a/Client/src/Pages/Monitors/Home/index.jsx b/Client/src/Pages/Monitors/Home/index.jsx index e17b56e37..9bc4496db 100644 --- a/Client/src/Pages/Monitors/Home/index.jsx +++ b/Client/src/Pages/Monitors/Home/index.jsx @@ -3,16 +3,15 @@ import { useEffect } from "react"; import { useSelector, useDispatch } from "react-redux"; import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { useNavigate } from "react-router-dom"; -import Button from "../../../Components/Button"; import { useTheme } from "@emotion/react"; -import BasicTable from "../../../Components/BasicTable"; -import { Box, Stack, Typography } from "@mui/material"; +import { Box, Button, Stack, Typography } from "@mui/material"; import PropTypes from "prop-types"; import SkeletonLayout from "./skeleton"; import Fallback from "./fallback"; import StatusBox from "./StatusBox"; -import { buildData } from "./monitorData"; import Breadcrumbs from "../../../Components/Breadcrumbs"; +import Greeting from "../../../Utils/greeting"; +import MonitorTable from "./MonitorTable"; const Monitors = ({ isAdmin }) => { const theme = useTheme(); @@ -24,43 +23,11 @@ const Monitors = ({ isAdmin }) => { useEffect(() => { dispatch(getUptimeMonitorsByTeamId(authState.authToken)); }, [authState.authToken, dispatch]); - - const monitorStats = monitorState.monitors.reduce( - (acc, monitor) => { - if (monitor.isActive === false) { - acc["paused"] += 1; - } else if (monitor.status === true) { - acc["up"] += 1; - } else { - acc["down"] += 1; - } - return acc; - }, - { paused: 0, up: 0, down: 0 } - ); - - const data = buildData(monitorState.monitors, isAdmin, navigate); - - let loading = monitorState.isLoading && monitorState.monitors.length === 0; - - const now = new Date(); - const hour = now.getHours(); - - let greeting = ""; - let emoji = ""; - if (hour < 12) { - greeting = "morning"; - emoji = "🌅"; - } else if (hour < 18) { - greeting = "afternoon"; - emoji = "🌞"; - } else { - greeting = "evening"; - emoji = "🌙"; - } - + let loading = + monitorState?.isLoading && + monitorState?.monitorsSummary?.monitors?.length === 0; return ( - + {loading ? ( ) : ( @@ -73,67 +40,52 @@ const Monitors = ({ isAdmin }) => { alignItems="center" mt={theme.spacing(5)} > - - - - Good {greeting},{" "} - - - {authState.user.firstName} {emoji} - - - - Here’s an overview of your uptime monitors. - - - {monitorState.monitors?.length !== 0 && ( + + {monitorState?.monitorsSummary?.monitors?.length !== 0 && ( )} - {isAdmin && monitorState.monitors?.length === 0 && ( + {isAdmin && monitorState?.monitorsSummary?.monitors?.length === 0 && ( )} - {monitorState.monitors?.length !== 0 && ( + {monitorState?.monitorsSummary?.monitors?.length !== 0 && ( <> - - - + + + { { borderColor={theme.palette.border.light} backgroundColor={theme.palette.background.accent} > - {monitorState.monitors.length} + {monitorState?.monitorsSummary?.monitors?.monitors + ?.length || 0} {/* TODO - add search bar */} - + )} diff --git a/Client/src/Pages/Monitors/Home/monitorData.jsx b/Client/src/Pages/Monitors/Home/monitorData.jsx index c82a1fa95..afe943f4e 100644 --- a/Client/src/Pages/Monitors/Home/monitorData.jsx +++ b/Client/src/Pages/Monitors/Home/monitorData.jsx @@ -27,22 +27,52 @@ const data = { rows: [], }; +/** + * Builds table data for a list of monitors. + * + * @param {Array} monitors - An array of monitor objects containing information about each monitor. + * @param {boolean} isAdmin - Flag indicating if the current user is an admin. + * @param {Function} navigate - A function to navigate to the monitor detail page. + * @returns {Object} The data structure containing columns and rows for the table. + */ export const buildData = (monitors, isAdmin, navigate) => { const theme = useTheme(); data.rows = monitors.map((monitor, idx) => { + let uptimePercentage = ""; + let percentageColor = theme.palette.percentage.uptimeExcellent; + + // Determine uptime percentage and color based on the monitor's uptimePercentage value + if (monitor.uptimePercentage !== undefined) { + uptimePercentage = + monitor.uptimePercentage === 0 + ? "0" + : (monitor.uptimePercentage * 100).toFixed(2); + + percentageColor = + monitor.uptimePercentage < 0.25 + ? theme.palette.percentage.uptimePoor + : monitor.uptimePercentage < 0.5 + ? theme.palette.percentage.uptimeFair + : monitor.uptimePercentage < 0.75 + ? theme.palette.percentage.uptimeGood + : theme.palette.percentage.uptimeExcellent; + } + const params = { url: monitor.url, title: monitor.name, - percentage: 100, - percentageColor: - monitor.status === true - ? theme.palette.success.main - : theme.palette.error.text, - status: monitor.status === true ? "up" : "down", + percentage: uptimePercentage, + percentageColor, + status: + monitor.status === undefined + ? "pending" + : monitor.status === true + ? "up" + : "down", }; - // Reverse checks so latest check is on the right + // Reverse checks so the latest check is on the right const reversedChecks = monitor.checks.slice().reverse(); return { diff --git a/Client/src/Pages/NotFound/index.jsx b/Client/src/Pages/NotFound/index.jsx index 17949ce4f..7d7adf149 100644 --- a/Client/src/Pages/NotFound/index.jsx +++ b/Client/src/Pages/NotFound/index.jsx @@ -1,8 +1,7 @@ -import Button from "../../Components/Button"; import React from "react"; import PropTypes from "prop-types"; import NotFoundSvg from "../../../src/assets/Images/sushi_404.svg"; -import { Stack, Typography } from "@mui/material"; +import { Button, Stack, Typography } from "@mui/material"; import { useNavigate } from "react-router"; import { useTheme } from "@emotion/react"; @@ -48,11 +47,13 @@ const NotFound = ({ title = DefaultValue.title, desc = DefaultValue.desc }) => { {desc} ); diff --git a/Client/src/Pages/PageSpeed/Configure/index.jsx b/Client/src/Pages/PageSpeed/Configure/index.jsx index 756e52d2b..005583f2c 100644 --- a/Client/src/Pages/PageSpeed/Configure/index.jsx +++ b/Client/src/Pages/PageSpeed/Configure/index.jsx @@ -1,80 +1,36 @@ import { useEffect, useState } from "react"; import { useTheme } from "@emotion/react"; -import { Box, Modal, Skeleton, Stack, Typography } from "@mui/material"; +import { Box, Button, Modal, Stack, Typography } from "@mui/material"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate, useParams } from "react-router"; import { deletePageSpeed, + getPagespeedMonitorById, getPageSpeedByTeamId, updatePageSpeed, + pausePageSpeed, } from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; import { monitorValidation } from "../../../Validation/validation"; import { createToast } from "../../../Utils/toastUtils"; import { logger } from "../../../Utils/Logger"; -import Button from "../../../Components/Button"; import Field from "../../../Components/Inputs/Field"; import Select from "../../../Components/Inputs/Select"; import Checkbox from "../../../Components/Inputs/Checkbox"; import PauseCircleOutlineIcon from "@mui/icons-material/PauseCircleOutline"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import PulseDot from "../../../Components/Animated/PulseDot"; - +import LoadingButton from "@mui/lab/LoadingButton"; +import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded"; +import SkeletonLayout from "./skeleton"; import "./index.css"; -/** - * Renders a skeleton layout. - * - * @returns {JSX.Element} - */ -const SkeletonLayout = () => { - const theme = useTheme(); - - return ( - <> - - - - - - - - - - - - - - - - - - - - ); -}; - const PageSpeedConfigure = () => { const theme = useTheme(); const navigate = useNavigate(); const dispatch = useDispatch(); const MS_PER_MINUTE = 60000; const { authToken } = useSelector((state) => state.auth); - const { monitors } = useSelector((state) => state.pageSpeedMonitors); + const { isLoading } = useSelector((state) => state.pageSpeedMonitors); const { monitorId } = useParams(); const [monitor, setMonitor] = useState({}); const [errors, setErrors] = useState({}); @@ -90,15 +46,25 @@ const PageSpeedConfigure = () => { ]; useEffect(() => { - const data = monitors.find((monitor) => monitor._id === monitorId); - if (!data) { - logger.error("Error fetching pagespeed monitor of id: " + monitorId); - navigate("/not-found", { replace: true }); - } - setMonitor({ - ...data, - }); - }, [monitorId, monitors, navigate]); + const fetchMonitor = async () => { + try { + const action = await dispatch( + getPagespeedMonitorById({ authToken, monitorId }) + ); + + if (getPagespeedMonitorById.fulfilled.match(action)) { + const monitor = action.payload.data; + setMonitor(monitor); + } else if (getPagespeedMonitorById.rejected.match(action)) { + throw new Error(action.error.message); + } + } catch (error) { + logger.error("Error fetching monitor of id: " + monitorId); + navigate("/not-found", { replace: true }); + } + }; + fetchMonitor(); + }, [dispatch, authToken, monitorId, navigate]); const handleChange = (event, id) => { let { value } = event.target; @@ -120,6 +86,21 @@ const PageSpeedConfigure = () => { }); }; + const handlePause = async () => { + try { + const action = await dispatch(pausePageSpeed({ authToken, monitorId })); + if (pausePageSpeed.fulfilled.match(action)) { + const monitor = action.payload.data; + setMonitor(monitor); + } else if (pausePageSpeed.rejected.match(action)) { + throw new Error(action.error.message); + } + } catch (error) { + logger.error("Error pausing monitor: " + monitorId); + createToast({ body: "Failed to pause monitor" }); + } + }; + const handleSave = async (event) => { event.preventDefault(); const action = await dispatch( @@ -144,11 +125,9 @@ const PageSpeedConfigure = () => { } }; - let loading = Object.keys(monitor).length === 0; - return ( - {loading ? ( + {Object.keys(monitor).length === 0 ? ( ) : ( <> @@ -196,30 +175,46 @@ const PageSpeedConfigure = () => { - + diff --git a/Client/src/Pages/PageSpeed/Configure/skeleton.jsx b/Client/src/Pages/PageSpeed/Configure/skeleton.jsx new file mode 100644 index 000000000..301a00e52 --- /dev/null +++ b/Client/src/Pages/PageSpeed/Configure/skeleton.jsx @@ -0,0 +1,51 @@ +import { Box, Skeleton, Stack } from "@mui/material"; +import { useTheme } from "@emotion/react"; + +/** + * Renders a skeleton layout. + * + * @returns {JSX.Element} + */ +const SkeletonLayout = () => { + const theme = useTheme(); + + return ( + <> + + + + + + + + + + + + + + + + + + + + ); +}; + +export default SkeletonLayout; diff --git a/Client/src/Pages/PageSpeed/CreatePageSpeed/index.css b/Client/src/Pages/PageSpeed/CreatePageSpeed/index.css index 4ac8d4a10..4b46fd3f0 100644 --- a/Client/src/Pages/PageSpeed/CreatePageSpeed/index.css +++ b/Client/src/Pages/PageSpeed/CreatePageSpeed/index.css @@ -22,6 +22,7 @@ .create-page-speed .section-disabled { opacity: 0.4; padding: 10px; + margin-right: -5px; border-radius: 8px; user-select: none; pointer-events: none; diff --git a/Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx b/Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx index 342eefc71..ecf7a2eb5 100644 --- a/Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx +++ b/Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx @@ -1,27 +1,136 @@ -import { Box, Stack, Typography } from "@mui/material"; import { useState } from "react"; +import { Box, Button, ButtonGroup, Stack, Typography } from "@mui/material"; +import { useSelector, useDispatch } from "react-redux"; +import { monitorValidation } from "../../../Validation/validation"; +import { useNavigate } from "react-router-dom"; import { useTheme } from "@emotion/react"; -import { useDispatch, useSelector } from "react-redux"; -import { useNavigate } from "react-router"; +import { createPageSpeed } from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; +import { createToast } from "../../../Utils/toastUtils"; +import { logger } from "../../../Utils/Logger"; +import { ConfigBox } from "../../Monitors/styled"; +import Radio from "../../../Components/Inputs/Radio"; import Field from "../../../Components/Inputs/Field"; import Select from "../../../Components/Inputs/Select"; -import Button from "../../../Components/Button"; import Checkbox from "../../../Components/Inputs/Checkbox"; -import { monitorValidation } from "../../../Validation/validation"; -import { createToast } from "../../../Utils/toastUtils"; -import { createPageSpeed } from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; import Breadcrumbs from "../../../Components/Breadcrumbs"; import "./index.css"; -import { logger } from "../../../Utils/Logger"; const CreatePageSpeed = () => { - const theme = useTheme(); - const navigate = useNavigate(); - const dispatch = useDispatch(); - const MS_PER_MINUTE = 60000; const { user, authToken } = useSelector((state) => state.auth); + const dispatch = useDispatch(); + const navigate = useNavigate(); + const theme = useTheme(); + const idMap = { + "monitor-url": "url", + "monitor-name": "name", + "monitor-checks-http": "type", + "monitor-checks-ping": "type", + "notify-email-default": "notification-email", + }; + + const [monitor, setMonitor] = useState({ + url: "", + name: "", + type: "pagespeed", + notifications: [], + interval: 3, + }); + const [https, setHttps] = useState(true); + const [errors, setErrors] = useState({}); + + const handleChange = (event, name) => { + const { value, id } = event.target; + if (!name) name = idMap[id]; + + if (name.includes("notification-")) { + name = name.replace("notification-", ""); + let hasNotif = monitor.notifications.some( + (notification) => notification.type === name + ); + setMonitor((prev) => { + const notifs = [...prev.notifications]; + if (hasNotif) { + return { + ...prev, + notifications: notifs.filter((notif) => notif.type !== name), + }; + } else { + return { + ...prev, + notifications: [ + ...notifs, + name === "email" + ? { type: name, address: value } + : // TODO - phone number + { type: name, phone: value }, + ], + }; + } + }); + } else { + setMonitor((prev) => ({ + ...prev, + [name]: value, + })); + + const { error } = monitorValidation.validate( + { [name]: value }, + { abortEarly: false } + ); + + setErrors((prev) => { + const updatedErrors = { ...prev }; + if (error) updatedErrors[name] = error.details[0].message; + else delete updatedErrors[name]; + return updatedErrors; + }); + } + }; + + const handleCreateMonitor = async (event) => { + event.preventDefault(); + //obj to submit + let form = { + url: `http${https ? "s" : ""}://` + monitor.url, + name: monitor.name === "" ? monitor.url : monitor.name, + type: monitor.type, + interval: monitor.interval * MS_PER_MINUTE, + }; + + const { error } = monitorValidation.validate(form, { + abortEarly: false, + }); + + if (error) { + const newErrors = {}; + error.details.forEach((err) => { + newErrors[err.path[0]] = err.message; + }); + setErrors(newErrors); + createToast({ body: "Error validation data." }); + } else { + form = { + ...form, + description: form.name, + teamId: user.teamId, + userId: user._id, + notifications: monitor.notifications, + }; + const action = await dispatch( + createPageSpeed({ authToken, monitor: form }) + ); + if (action.meta.requestStatus === "fulfilled") { + createToast({ body: "Monitor created successfully!" }); + navigate("/pagespeed"); + } else { + createToast({ body: "Failed to create monitor." }); + } + } + }; + + //select values const frequencies = [ { _id: 3, name: "3 minutes" }, { _id: 5, name: "5 minutes" }, @@ -31,75 +140,15 @@ const CreatePageSpeed = () => { { _id: 1440, name: "1 day" }, { _id: 10080, name: "1 week" }, ]; - - const [form, setForm] = useState({ - name: "", - url: "", - interval: 3, - }); - const [errors, setErrors] = useState({}); - - const handleChange = (event, id) => { - const { value } = event.target; - setForm((prev) => ({ ...prev, [id]: value })); - - const { error } = monitorValidation.validate( - { [id]: value }, - { abortEarly: false } - ); - - setErrors((prev) => { - const newErrors = { ...prev }; - if (error) newErrors[id] = error.details[0].message; - else delete newErrors[id]; - return newErrors; - }); - }; - - const handleCreate = async (event) => { - event.preventDefault(); - - let monitor = { - url: "http://" + form.url, - name: form.name === "" ? form.url : form.name, - }; - - const { error } = monitorValidation.validate(form, { abortEarly: false }); - - if (error) { - const newErrors = {}; - error.details.forEach((err) => { - newErrors[err.path[0]] = err.message; - }); - setErrors(newErrors); - createToast({ body: "Error validating data." }); - } else { - monitor = { - ...monitor, - description: monitor.name, - userId: user._id, - teamId: user.teamId, - interval: form.interval * MS_PER_MINUTE, - type: "pagespeed", - }; - try { - const action = await dispatch(createPageSpeed({ authToken, monitor })); - if (action.meta.requestStatus === "fulfilled") { - navigate("/pagespeed"); - } - } catch (error) { - createToast({ - body: - error.details && error.details.length > 0 - ? error.details[0].message - : "Unknown error.", - }); - } - } - }; - return ( - + { /> - + { Create your{" "} - pagespeed{" "} - - - monitor + Pagespeed monitor - - - Monitor display name + + + General settings + + Here you can select the URL of the host, together with the type of + monitor. + + + + handleChange(event, "name")} - error={errors.name} + label="Display name" + isOptional={true} + placeholder="Google" + value={monitor.name} + onChange={handleChange} + error={errors["name"]} /> - - URL - handleChange(event, "url")} - error={errors.url} - /> - - - Check frequency - handleChange(event, "interval")} + items={frequencies} + /> + + + - + ); }; diff --git a/Client/src/Pages/PageSpeed/Details/index.jsx b/Client/src/Pages/PageSpeed/Details/index.jsx index 05488d39f..4004e1715 100644 --- a/Client/src/Pages/PageSpeed/Details/index.jsx +++ b/Client/src/Pages/PageSpeed/Details/index.jsx @@ -1,5 +1,5 @@ import PropTypes from "prop-types"; -import { Box, Skeleton, Stack, Typography } from "@mui/material"; +import { Box, Button, Skeleton, Stack, Typography } from "@mui/material"; import { PieChart } from "@mui/x-charts/PieChart"; import { useDrawingArea } from "@mui/x-charts"; import { useEffect, useState } from "react"; @@ -12,7 +12,6 @@ import { } from "../../../Utils/timeUtils"; import { logger } from "../../../Utils/Logger"; import { networkService } from "../../../main"; -import Button from "../../../Components/Button"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; import LastCheckedIcon from "../../../assets/icons/calendar-check.svg?react"; import ClockIcon from "../../../assets/icons/maintenance.svg?react"; @@ -43,7 +42,7 @@ const StatBox = ({ icon, title, value }) => { {title} @@ -214,7 +213,7 @@ const PageSpeedDetails = () => { monitorId, "desc", 50, - null, + "day", null, null ); @@ -398,28 +397,24 @@ const PageSpeedDetails = () => { { { { + const theme = useTheme(); + const navigate = useNavigate(); + + return ( + .MuiStack-root": { + backgroundColor: theme.palette.background.accent, + }, + }} + > + navigate(`/pagespeed/${data._id}`)} + border={1} + borderColor={theme.palette.border.light} + borderRadius={theme.shape.borderRadius} + backgroundColor={theme.palette.background.main} + sx={{ + cursor: "pointer", + "& svg path": { stroke: theme.palette.other.icon, strokeWidth: 0.8 }, + }} + > + + + + + {data.name} + + + + + {data.url.replace(/^https?:\/\//, "")} + + + + Last checked:{" "} + + {formatDate(getLastChecked(data.checks, false))}{" "} + + ({formatDurationRounded(getLastChecked(data.checks))} ago) + + + + + + ); +}; + +Card.propTypes = { + data: PropTypes.object.isRequired, +}; + +export default Card; diff --git a/Client/src/Pages/PageSpeed/index.css b/Client/src/Pages/PageSpeed/index.css index a970ccd70..83935dde0 100644 --- a/Client/src/Pages/PageSpeed/index.css +++ b/Client/src/Pages/PageSpeed/index.css @@ -1,14 +1,13 @@ .page-speed h2.MuiTypography-root { line-height: 1.1; } -.page-speed h1.MuiTypography-root, +.page-speed:not(:has([class*="fallback__"])) h1.MuiTypography-root { + font-size: var(--env-var-font-size-large-plus); +} .page-speed h2.MuiTypography-root { font-size: var(--env-var-font-size-large); font-weight: 600; } -.page-speed p.MuiTypography-root { - font-size: var(--env-var-font-size-medium); -} .page-speed p:has(> span.MuiTypography-root), .page-speed p.MuiTypography-root > span.MuiTypography-root { font-size: var(--env-var-font-size-small-plus); @@ -20,5 +19,4 @@ } .page-speed:not(:has([class*="fallback__"])) button { height: 34px; - align-self: flex-end; } diff --git a/Client/src/Pages/PageSpeed/index.jsx b/Client/src/Pages/PageSpeed/index.jsx index a96eefe3b..ba65bf436 100644 --- a/Client/src/Pages/PageSpeed/index.jsx +++ b/Client/src/Pages/PageSpeed/index.jsx @@ -1,141 +1,16 @@ -import { Box, Grid, Skeleton, Stack, Typography } from "@mui/material"; +import { Box, Button, Grid, Stack } from "@mui/material"; import { useEffect } from "react"; import { useTheme } from "@emotion/react"; -import { formatDate, formatDurationRounded } from "../../Utils/timeUtils"; -import { StatusLabel } from "../../Components/Label"; import { useDispatch, useSelector } from "react-redux"; import { getPageSpeedByTeamId } from "../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; -import PageSpeedIcon from "../../assets/icons/page-speed.svg?react"; import Fallback from "../../Components/Fallback"; import "./index.css"; -import Button from "../../Components/Button"; import { useNavigate } from "react-router"; -import { getLastChecked } from "../../Utils/monitorUtils"; import PropTypes from "prop-types"; - -const Card = ({ data }) => { - const theme = useTheme(); - const navigate = useNavigate(); - - return ( - .MuiStack-root": { - backgroundColor: "var(--primary-bg-accent)", - }, - }} - > - navigate(`/pagespeed/${data._id}`)} - border={1} - borderColor={theme.palette.border.light} - borderRadius={theme.shape.borderRadius} - backgroundColor={theme.palette.background.main} - sx={{ cursor: "pointer" }} - > - - - - - {data.name} - - - - {data.url.replace(/^https?:\/\//, "")} - - - Last checked:{" "} - - {formatDate(getLastChecked(data.checks, false))}{" "} - - ({formatDurationRounded(getLastChecked(data.checks))} ago) - - - - - - ); -}; - -Card.propTypes = { - data: PropTypes.object.isRequired, -}; - -/** - * Renders a skeleton layout. - * - * @returns {JSX.Element} - */ -const SkeletonLayout = () => { - const theme = useTheme(); - - return ( - - - - - - - - - - - - - - - - ); -}; +import Breadcrumbs from "../../Components/Breadcrumbs"; +import Greeting from "../../Utils/greeting"; +import SkeletonLayout from "./skeleton"; +import Card from "./card"; const PageSpeed = ({ isAdmin }) => { const theme = useTheme(); @@ -143,7 +18,7 @@ const PageSpeed = ({ isAdmin }) => { const navigate = useNavigate(); const { authToken } = useSelector((state) => state.auth); - const { monitors, isLoading } = useSelector( + const { monitorsSummary, isLoading } = useSelector( (state) => state.pageSpeedMonitors ); useEffect(() => { @@ -152,12 +27,11 @@ const PageSpeed = ({ isAdmin }) => { // will show skeletons only on initial load // since monitor state is being added to redux persist, there's no reason to display skeletons on every render - let isActuallyLoading = isLoading && monitors.length === 0; + let isActuallyLoading = isLoading && monitorsSummary?.monitors?.length === 0; return ( [class*="fallback__"])': { position: "relative", @@ -172,38 +46,38 @@ const PageSpeed = ({ isAdmin }) => { > {isActuallyLoading ? ( - ) : monitors?.length !== 0 ? ( - - - - All page speed monitors - - Click on one of the monitors to get more site speed information. - - - + + - {monitors?.map((monitor) => ( - + {monitorsSummary?.monitors?.map((monitor) => ( + ))} - + ) : ( { + const theme = useTheme(); + + return ( + + + + + + + + + + + + + + + + ); +}; + +export default SkeletonLayout; diff --git a/Client/src/Pages/Settings/index.jsx b/Client/src/Pages/Settings/index.jsx index d908e33c1..d1f15ea8c 100644 --- a/Client/src/Pages/Settings/index.jsx +++ b/Client/src/Pages/Settings/index.jsx @@ -1,14 +1,40 @@ import { useTheme } from "@emotion/react"; -import { Box, Stack, styled, Typography } from "@mui/material"; -import Button from "../../Components/Button"; +import { Box, Button, Stack, styled, Typography } from "@mui/material"; import Field from "../../Components/Inputs/Field"; import Link from "../../Components/Link"; import Select from "../../Components/Inputs/Select"; import { logger } from "../../Utils/Logger"; import "./index.css"; - -const Settings = () => { +import { useDispatch, useSelector } from "react-redux"; +import { createToast } from "../../Utils/toastUtils"; +import { deleteMonitorChecksByTeamId } from "../../Features/UptimeMonitors/uptimeMonitorsSlice"; +import PropTypes from "prop-types"; +import LoadingButton from "@mui/lab/LoadingButton"; +const Settings = ({ isAdmin }) => { const theme = useTheme(); + const { user, authToken } = useSelector((state) => state.auth); + const { isLoading } = useSelector((state) => state.uptimeMonitors); + + const dispatch = useDispatch(); + + // TODO Handle saving + + const handleClearStats = async () => { + try { + const action = await dispatch( + deleteMonitorChecksByTeamId({ teamId: user.teamId, authToken }) + ); + + if (deleteMonitorChecksByTeamId.fulfilled.match(action)) { + createToast({ body: "Stats cleared successfully" }); + } else { + createToast({ body: "Failed to clear stats" }); + } + } catch (error) { + logger.error(error); + createToast({ body: "Failed to clear stats" }); + } + }; const ConfigBox = styled("div")({ display: "flex", @@ -79,35 +105,41 @@ const Settings = () => { /> - - - History and monitoring - - Define here for how long you want to keep the data. You can also - remove all past data. - - - - logger.warn("Disabled")} - /> + {isAdmin && ( + - Clear all stats. This is irreversible. -