Merge branch 'develop' into enhancement/check-if-url-resolves

This commit is contained in:
om-3004 committed 2024-10-18 11:39:07 +05:30
commit 34a13530b3
202 files changed
+33101 -32065

No files matched your search

+14 -14
View File
@@ -1,16 +1,16 @@
{ {
"printWidth": 90, "printWidth": 90,
"useTabs": true, "useTabs": true,
"tabWidth": 2, "tabWidth": 2,
"singleQuote": false, "singleQuote": false,
"bracketSpacing": true, "bracketSpacing": true,
"proseWrap": "preserve", "proseWrap": "preserve",
"bracketSameLine": false, "bracketSameLine": false,
"singleAttributePerLine": true, "singleAttributePerLine": true,
"semi": true, "semi": true,
"jsx-single-quote": false, "jsxSingleQuote": false,
"quoteProps": "as-needed", "quoteProps": "as-needed",
"arrowParens": "always", "arrowParens": "always",
"trailingComma": "es5", "trailingComma": "es5",
"htmlWhitespaceSensitivity": "css" "htmlWhitespaceSensitivity": "css"
} }
+17 -20
View File
@@ -1,21 +1,18 @@
module.exports = { module.exports = {
root: true, root: true,
env: { browser: true, es2020: true }, env: { browser: true, es2020: true },
extends: [ extends: [
'eslint:recommended', "eslint:recommended",
'plugin:react/recommended', "plugin:react/recommended",
'plugin:react/jsx-runtime', "plugin:react/jsx-runtime",
'plugin:react-hooks/recommended', "plugin:react-hooks/recommended",
], ],
ignorePatterns: ['dist', '.eslintrc.cjs'], ignorePatterns: ["dist", ".eslintrc.cjs"],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, parserOptions: { ecmaVersion: "latest", sourceType: "module" },
settings: { react: { version: '18.2' } }, settings: { react: { version: "18.2" } },
plugins: ['react-refresh'], plugins: ["react-refresh"],
rules: { rules: {
'react/jsx-no-target-blank': 'off', "react/jsx-no-target-blank": "off",
'react-refresh/only-export-components': [ "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
'warn', },
{ allowConstantExport: true }, };
],
},
}
+20 -11
View File
@@ -1,14 +1,23 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" href="./bluewave_favicon.ico" /> <link
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> rel="icon"
<title>BlueWave Uptime</title> href="./bluewave_favicon.ico"
</head> />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>BlueWave Uptime</title>
</head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.jsx"></script> <script
</body> type="module"
src="/src/main.jsx"
></script>
</body>
</html> </html>
+6501 -6501
View File
File diff suppressed because it is too large. Load diff
+47 -47
View File
@@ -1,49 +1,49 @@
{ {
"name": "client", "name": "client",
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.11.4", "@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.5", "@emotion/styled": "^11.11.5",
"@fontsource/roboto": "^5.0.13", "@fontsource/roboto": "^5.0.13",
"@mui/icons-material": "^5.15.17", "@mui/icons-material": "^5.15.17",
"@mui/lab": "^5.0.0-alpha.170", "@mui/lab": "^5.0.0-alpha.170",
"@mui/material": "^5.15.16", "@mui/material": "^5.15.16",
"@mui/x-charts": "^7.5.1", "@mui/x-charts": "^7.5.1",
"@mui/x-data-grid": "7.3.2", "@mui/x-data-grid": "7.3.2",
"@mui/x-date-pickers": "7.3.2", "@mui/x-date-pickers": "7.3.2",
"@reduxjs/toolkit": "2.2.5", "@reduxjs/toolkit": "2.2.5",
"axios": "^1.7.4", "axios": "^1.7.4",
"chart.js": "^4.4.3", "chart.js": "^4.4.3",
"dayjs": "1.11.11", "dayjs": "1.11.11",
"joi": "17.13.1", "joi": "17.13.1",
"jwt-decode": "^4.0.0", "jwt-decode": "^4.0.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-redux": "9.1.2", "react-redux": "9.1.2",
"react-router": "^6.23.0", "react-router": "^6.23.0",
"react-router-dom": "^6.23.1", "react-router-dom": "^6.23.1",
"react-toastify": "^10.0.5", "react-toastify": "^10.0.5",
"recharts": "2.13.0-alpha.4", "recharts": "2.13.0-alpha.4",
"redux-persist": "6.0.0", "redux-persist": "6.0.0",
"vite-plugin-svgr": "^4.2.0" "vite-plugin-svgr": "^4.2.0"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "^18.2.66", "@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22", "@types/react-dom": "^18.2.22",
"@vitejs/plugin-react": "^4.2.1", "@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.0", "eslint": "^8.57.0",
"eslint-plugin-react": "^7.34.1", "eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6", "eslint-plugin-react-refresh": "^0.4.6",
"prettier": "^3.3.3", "prettier": "^3.3.3",
"vite": "^5.2.0" "vite": "^5.2.0"
} }
} }
+165 -165
View File
@@ -40,177 +40,177 @@ import { getAppSettings } from "./Features/Settings/settingsSlice";
import { logger } from "./Utils/Logger"; // Import the logger import { logger } from "./Utils/Logger"; // Import the logger
import { networkService } from "./main"; import { networkService } from "./main";
function App() { function App() {
const AdminCheckedRegister = withAdminCheck(Register); const AdminCheckedRegister = withAdminCheck(Register);
const MonitorsWithAdminProp = withAdminProp(Monitors); const MonitorsWithAdminProp = withAdminProp(Monitors);
const MonitorDetailsWithAdminProp = withAdminProp(Details); const MonitorDetailsWithAdminProp = withAdminProp(Details);
const PageSpeedWithAdminProp = withAdminProp(PageSpeed); const PageSpeedWithAdminProp = withAdminProp(PageSpeed);
const PageSpeedDetailsWithAdminProp = withAdminProp(PageSpeedDetails); const PageSpeedDetailsWithAdminProp = withAdminProp(PageSpeedDetails);
const MaintenanceWithAdminProp = withAdminProp(Maintenance); const MaintenanceWithAdminProp = withAdminProp(Maintenance);
const SettingsWithAdminProp = withAdminProp(Settings); const SettingsWithAdminProp = withAdminProp(Settings);
const AdvancedSettingsWithAdminProp = withAdminProp(AdvancedSettings); const AdvancedSettingsWithAdminProp = withAdminProp(AdvancedSettings);
const mode = useSelector((state) => state.ui.mode); const mode = useSelector((state) => state.ui.mode);
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const dispatch = useDispatch(); const dispatch = useDispatch();
useEffect(() => { useEffect(() => {
if (authToken) { if (authToken) {
dispatch(getAppSettings({ authToken })); dispatch(getAppSettings({ authToken }));
} }
}, [dispatch, authToken]); }, [dispatch, authToken]);
// Cleanup // Cleanup
useEffect(() => { useEffect(() => {
return () => { return () => {
logger.cleanup(); logger.cleanup();
networkService.cleanup(); networkService.cleanup();
}; };
}, []); }, []);
return ( return (
<ThemeProvider theme={mode === "light" ? lightTheme : darkTheme}> <ThemeProvider theme={mode === "light" ? lightTheme : darkTheme}>
<CssBaseline /> <CssBaseline />
<Routes> <Routes>
<Route <Route
exact exact
path="/" path="/"
element={<HomeLayout />} element={<HomeLayout />}
> >
<Route <Route
exact exact
path="/" path="/"
element={<ProtectedRoute Component={MonitorsWithAdminProp} />} element={<ProtectedRoute Component={MonitorsWithAdminProp} />}
/> />
<Route <Route
path="/monitors" path="/monitors"
element={<ProtectedRoute Component={MonitorsWithAdminProp} />} element={<ProtectedRoute Component={MonitorsWithAdminProp} />}
/> />
<Route <Route
path="/monitors/create/:monitorId?" path="/monitors/create/:monitorId?"
element={<ProtectedRoute Component={CreateMonitor} />} element={<ProtectedRoute Component={CreateMonitor} />}
/> />
<Route <Route
path="/monitors/:monitorId/" path="/monitors/:monitorId/"
element={<ProtectedRoute Component={MonitorDetailsWithAdminProp} />} element={<ProtectedRoute Component={MonitorDetailsWithAdminProp} />}
/> />
<Route <Route
path="/monitors/configure/:monitorId/" path="/monitors/configure/:monitorId/"
element={<ProtectedRoute Component={Configure} />} element={<ProtectedRoute Component={Configure} />}
/> />
<Route <Route
path="incidents/:monitorId?" path="incidents/:monitorId?"
element={<ProtectedRoute Component={Incidents} />} element={<ProtectedRoute Component={Incidents} />}
/> />
<Route <Route
path="status" path="status"
element={<ProtectedRoute Component={Status} />} element={<ProtectedRoute Component={Status} />}
/> />
<Route <Route
path="integrations" path="integrations"
element={<ProtectedRoute Component={Integrations} />} element={<ProtectedRoute Component={Integrations} />}
/> />
<Route <Route
path="maintenance" path="maintenance"
element={<ProtectedRoute Component={MaintenanceWithAdminProp} />} element={<ProtectedRoute Component={MaintenanceWithAdminProp} />}
/> />
<Route <Route
path="/maintenance/create/:maintenanceWindowId?" path="/maintenance/create/:maintenanceWindowId?"
element={<CreateNewMaintenanceWindow />} element={<CreateNewMaintenanceWindow />}
/> />
<Route <Route
path="settings" path="settings"
element={<ProtectedRoute Component={SettingsWithAdminProp} />} element={<ProtectedRoute Component={SettingsWithAdminProp} />}
/> />
<Route <Route
path="advanced-settings" path="advanced-settings"
element={<ProtectedRoute Component={AdvancedSettingsWithAdminProp} />} element={<ProtectedRoute Component={AdvancedSettingsWithAdminProp} />}
/> />
<Route <Route
path="account/profile" path="account/profile"
element={ element={
<ProtectedRoute <ProtectedRoute
Component={Account} Component={Account}
open="profile" open="profile"
/> />
} }
/> />
<Route <Route
path="account/password" path="account/password"
element={ element={
<ProtectedRoute <ProtectedRoute
Component={Account} Component={Account}
open="password" open="password"
/> />
} }
/> />
<Route <Route
path="account/team" path="account/team"
element={ element={
<ProtectedRoute <ProtectedRoute
Component={Account} Component={Account}
open="team" open="team"
/> />
} }
/> />
<Route <Route
path="pagespeed" path="pagespeed"
element={<ProtectedRoute Component={PageSpeedWithAdminProp} />} element={<ProtectedRoute Component={PageSpeedWithAdminProp} />}
/> />
<Route <Route
path="pagespeed/create" path="pagespeed/create"
element={<ProtectedRoute Component={CreatePageSpeed} />} element={<ProtectedRoute Component={CreatePageSpeed} />}
/> />
<Route <Route
path="pagespeed/:monitorId" path="pagespeed/:monitorId"
element={<ProtectedRoute Component={PageSpeedDetailsWithAdminProp} />} element={<ProtectedRoute Component={PageSpeedDetailsWithAdminProp} />}
/> />
<Route <Route
path="pagespeed/configure/:monitorId" path="pagespeed/configure/:monitorId"
element={<ProtectedRoute Component={PageSpeedConfigure} />} element={<ProtectedRoute Component={PageSpeedConfigure} />}
/> />
</Route> </Route>
<Route <Route
exact exact
path="/login" path="/login"
element={<Login />} element={<Login />}
/> />
<Route <Route
exact exact
path="/register" path="/register"
element={<AdminCheckedRegister />} element={<AdminCheckedRegister />}
/> />
<Route <Route
exact exact
path="/register/:token" path="/register/:token"
element={<Register />} element={<Register />}
/> />
{/* <Route path="/toast" element={<ToastComponent />} /> */} {/* <Route path="/toast" element={<ToastComponent />} /> */}
<Route <Route
path="*" path="*"
element={<NotFound />} element={<NotFound />}
/> />
<Route <Route
path="/forgot-password" path="/forgot-password"
element={<ForgotPassword />} element={<ForgotPassword />}
/> />
<Route <Route
path="/check-email" path="/check-email"
element={<CheckEmail />} element={<CheckEmail />}
/> />
<Route <Route
path="/set-new-password/:token" path="/set-new-password/:token"
element={<SetNewPassword />} element={<SetNewPassword />}
/> />
<Route <Route
path="/new-password-confirmed" path="/new-password-confirmed"
element={<NewPasswordConfirmed />} element={<NewPasswordConfirmed />}
/> />
</Routes> </Routes>
<ToastContainer /> <ToastContainer />
</ThemeProvider> </ThemeProvider>
); );
} }
export default App; export default App;
+3 -3
View File
@@ -1,9 +1,9 @@
.alert { .alert {
margin: 0; margin: 0;
width: fit-content; width: fit-content;
} }
.alert, .alert,
.alert button, .alert button,
.alert .MuiTypography-root { .alert .MuiTypography-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
+85 -87
View File
@@ -13,9 +13,9 @@ import "./index.css";
*/ */
const icons = { const icons = {
info: <InfoOutlinedIcon />, info: <InfoOutlinedIcon />,
error: <ErrorOutlineOutlinedIcon />, error: <ErrorOutlineOutlinedIcon />,
warning: <WarningAmberOutlinedIcon />, warning: <WarningAmberOutlinedIcon />,
}; };
/** /**
@@ -30,94 +30,92 @@ const icons = {
*/ */
const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => { const Alert = ({ variant, title, body, isToast, hasIcon = true, onClick }) => {
const theme = useTheme(); const theme = useTheme();
const { text, bg, border } = theme.palette[variant]; const { text, bg, border } = theme.palette[variant];
const icon = icons[variant]; const icon = icons[variant];
return ( return (
<Stack <Stack
direction="row" direction="row"
justifyContent="flex-start" justifyContent="flex-start"
alignItems={hasIcon ? "" : "center"} alignItems={hasIcon ? "" : "center"}
className="alert row-stack" className="alert row-stack"
gap={theme.spacing(8)} gap={theme.spacing(8)}
sx={{ sx={{
padding: hasIcon padding: hasIcon ? theme.spacing(8) : `${theme.spacing(4)} ${theme.spacing(8)}`,
? theme.spacing(8) backgroundColor: bg,
: `${theme.spacing(4)} ${theme.spacing(8)}`, border: `solid 1px ${border}`,
backgroundColor: bg, borderRadius: theme.shape.borderRadius,
border: `solid 1px ${border}`, }}
borderRadius: theme.shape.borderRadius, >
}} {hasIcon && <Box sx={{ color: text }}>{icon}</Box>}
> <Stack
{hasIcon && <Box sx={{ color: text }}>{icon}</Box>} direction="column"
<Stack direction="column" gap="2px" sx={{ flex: 1 }}> gap="2px"
{title && ( sx={{ flex: 1 }}
<Typography sx={{ fontWeight: "700", color: `${text}` }}> >
{title} {title && (
</Typography> <Typography sx={{ fontWeight: "700", color: `${text}` }}>{title}</Typography>
)} )}
{body && ( {body && (
<Typography sx={{ fontWeight: "400", color: `${text}` }}> <Typography sx={{ fontWeight: "400", color: `${text}` }}>{body}</Typography>
{body} )}
</Typography> {hasIcon && isToast && (
)} <Button
{hasIcon && isToast && ( variant="text"
<Button color="info"
variant="text" onClick={onClick}
color="info" sx={{
onClick={onClick} fontWeight: "600",
sx={{ width: "fit-content",
fontWeight: "600", mt: theme.spacing(4),
width: "fit-content", padding: 0,
mt: theme.spacing(4), minWidth: 0,
padding: 0, }}
minWidth: 0, >
}} Dismiss
> </Button>
Dismiss )}
</Button> </Stack>
)} {isToast && (
</Stack> <IconButton
{isToast && ( onClick={onClick}
<IconButton sx={{
onClick={onClick} alignSelf: "flex-start",
sx={{ ml: "auto",
alignSelf: "flex-start", mr: "-5px",
ml: "auto", mt: hasIcon ? "-5px" : 0,
mr: "-5px", padding: "5px",
mt: hasIcon ? "-5px" : 0, "&:focus": {
padding: "5px", outline: "none",
"&:focus": { },
outline: "none", }}
}, >
}} <CloseIcon
> sx={{
<CloseIcon fontSize: "20px",
sx={{ }}
fontSize: "20px", />
}} </IconButton>
/> )}
</IconButton> </Stack>
)} );
</Stack>
);
}; };
Alert.propTypes = { Alert.propTypes = {
variant: PropTypes.oneOf(["info", "error", "warning"]).isRequired, variant: PropTypes.oneOf(["info", "error", "warning"]).isRequired,
title: PropTypes.string, title: PropTypes.string,
body: PropTypes.string, body: PropTypes.string,
isToast: PropTypes.bool, isToast: PropTypes.bool,
hasIcon: PropTypes.bool, hasIcon: PropTypes.bool,
onClick: function (props, propName, componentName) { onClick: function (props, propName, componentName) {
if (props.isToast && !props[propName]) { if (props.isToast && !props[propName]) {
return new Error( return new Error(
`Prop '${propName}' is required when 'isToast' is true in '${componentName}'.` `Prop '${propName}' is required when 'isToast' is true in '${componentName}'.`
); );
} }
return null; return null;
}, },
}; };
export default Alert; export default Alert;
+39 -39
View File
@@ -15,48 +15,48 @@ import { Box, Stack } from "@mui/material";
*/ */
const PulseDot = ({ color }) => { const PulseDot = ({ color }) => {
return ( return (
<Stack <Stack
width="26px" width="26px"
height="24px" height="24px"
alignItems="center" alignItems="center"
justifyContent="center" justifyContent="center"
> >
<Box <Box
minWidth="18px" minWidth="18px"
minHeight="18px" minHeight="18px"
sx={{ sx={{
position: "relative", position: "relative",
backgroundColor: color, backgroundColor: color,
borderRadius: "50%", borderRadius: "50%",
"&::before": { "&::before": {
content: `""`, content: `""`,
position: "absolute", position: "absolute",
width: "100%", width: "100%",
height: "100%", height: "100%",
backgroundColor: "inherit", backgroundColor: "inherit",
borderRadius: "50%", borderRadius: "50%",
animation: "ripple 1.8s ease-out infinite", animation: "ripple 1.8s ease-out infinite",
}, },
"&::after": { "&::after": {
content: `""`, content: `""`,
position: "absolute", position: "absolute",
width: "7px", width: "7px",
height: "7px", height: "7px",
borderRadius: "50%", borderRadius: "50%",
backgroundColor: "white", backgroundColor: "white",
top: "50%", top: "50%",
left: "50%", left: "50%",
transform: "translate(-50%, -50%)", transform: "translate(-50%, -50%)",
}, },
}} }}
/> />
</Stack> </Stack>
); );
}; };
PulseDot.propTypes = { PulseDot.propTypes = {
color: PropTypes.string.isRequired, color: PropTypes.string.isRequired,
}; };
export default PulseDot; export default PulseDot;
+51 -53
View File
@@ -9,19 +9,19 @@ import { useEffect, useState } from "react";
* @returns {string} * @returns {string}
*/ */
const stringToColor = (string) => { const stringToColor = (string) => {
let hash = 0; let hash = 0;
let i; let i;
for (i = 0; i < string.length; i += 1) { for (i = 0; i < string.length; i += 1) {
hash = string.charCodeAt(i) + ((hash << 5) - hash); hash = string.charCodeAt(i) + ((hash << 5) - hash);
} }
let color = "#"; let color = "#";
for (i = 0; i < 3; i += 1) { for (i = 0; i < 3; i += 1) {
const value = (hash >> (i * 8)) & 0xff; const value = (hash >> (i * 8)) & 0xff;
color += `00${value.toString(16)}`.slice(-2); color += `00${value.toString(16)}`.slice(-2);
} }
return color; return color;
}; };
/** /**
@@ -37,54 +37,52 @@ const stringToColor = (string) => {
*/ */
const Avatar = ({ src, small, sx }) => { const Avatar = ({ src, small, sx }) => {
const { user } = useSelector((state) => state.auth); const { user } = useSelector((state) => state.auth);
const style = small ? { width: 32, height: 32 } : { width: 64, height: 64 }; const style = small ? { width: 32, height: 32 } : { width: 64, height: 64 };
const border = small ? 1 : 3; const border = small ? 1 : 3;
const [image, setImage] = useState(); const [image, setImage] = useState();
useEffect(() => { useEffect(() => {
if (user.avatarImage) { if (user.avatarImage) {
setImage(`data:image/png;base64,${user.avatarImage}`); setImage(`data:image/png;base64,${user.avatarImage}`);
} }
}, [user?.avatarImage]); }, [user?.avatarImage]);
return ( return (
<MuiAvatar <MuiAvatar
alt={`${user?.firstName} ${user?.lastName}`} alt={`${user?.firstName} ${user?.lastName}`}
src={ src={src ? src : user?.avatarImage ? image : "/static/images/avatar/2.jpg"}
src ? src : user?.avatarImage ? image : "/static/images/avatar/2.jpg" sx={{
} fontSize: small ? "16px" : "22px",
sx={{ color: "white",
fontSize: small ? "16px" : "22px", fontWeight: 400,
color: "white", backgroundColor: stringToColor(`${user?.firstName} ${user?.lastName}`),
fontWeight: 400, display: "inline-flex",
backgroundColor: stringToColor(`${user?.firstName} ${user?.lastName}`), "&::before": {
display: "inline-flex", content: `""`,
"&::before": { position: "absolute",
content: `""`, top: 0,
position: "absolute", left: 0,
top: 0, width: `100%`,
left: 0, height: `100%`,
width: `100%`, border: `${border}px solid rgba(255,255,255,0.2)`,
height: `100%`, borderRadius: "50%",
border: `${border}px solid rgba(255,255,255,0.2)`, },
borderRadius: "50%", ...style,
}, ...sx,
...style, }}
...sx, >
}} {user.firstName?.charAt(0)}
> {user.lastName?.charAt(0)}
{user.firstName?.charAt(0)} </MuiAvatar>
{user.lastName?.charAt(0)} );
</MuiAvatar>
);
}; };
Avatar.propTypes = { Avatar.propTypes = {
src: PropTypes.string, src: PropTypes.string,
small: PropTypes.bool, small: PropTypes.bool,
sx: PropTypes.object, sx: PropTypes.object,
}; };
export default Avatar; export default Avatar;
+62 -65
View File
@@ -1,133 +1,130 @@
.MuiTable-root .host { .MuiTable-root .host {
width: fit-content; width: fit-content;
text-overflow: ellipsis; text-overflow: ellipsis;
overflow: hidden; overflow: hidden;
white-space: nowrap; white-space: nowrap;
} }
.MuiTable-root .host span { .MuiTable-root .host span {
font-size: 11px; font-size: 11px;
} }
.MuiTable-root .label { .MuiTable-root .label {
line-height: 1; line-height: 1;
border-radius: var(--env-var-radius-2); border-radius: var(--env-var-radius-2);
padding: 7px; padding: 7px;
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
} }
.MuiPaper-root:has(table.MuiTable-root) { .MuiPaper-root:has(table.MuiTable-root) {
box-shadow: none; box-shadow: none;
} }
.MuiTable-root .MuiTable-root .MuiTableBody-root .MuiTableRow-root:last-child .MuiTableCell-root {
.MuiTableBody-root border: none;
.MuiTableRow-root:last-child
.MuiTableCell-root {
border: none;
} }
.MuiTable-root .MuiTableHead-root .MuiTableCell-root, .MuiTable-root .MuiTableHead-root .MuiTableCell-root,
.MuiTable-root .MuiTableBody-root .MuiTableCell-root { .MuiTable-root .MuiTableBody-root .MuiTableCell-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.MuiTable-root .MuiTableHead-root .MuiTableCell-root { .MuiTable-root .MuiTableHead-root .MuiTableCell-root {
padding: var(--env-var-spacing-1) var(--env-var-spacing-2); padding: var(--env-var-spacing-1) var(--env-var-spacing-2);
font-weight: 500; font-weight: 500;
} }
.MuiTable-root .MuiTableHead-root span { .MuiTable-root .MuiTableHead-root span {
display: inline-block; display: inline-block;
height: 17px; height: 17px;
width: 20px; width: 20px;
overflow: hidden; overflow: hidden;
margin-bottom: -3px; margin-bottom: -3px;
margin-left: 3px; margin-left: 3px;
} }
.MuiTable-root .MuiTableHead-root span svg { .MuiTable-root .MuiTableHead-root span svg {
width: 20px; width: 20px;
height: 20px; height: 20px;
} }
.MuiTable-root .MuiTableBody-root .MuiTableCell-root { .MuiTable-root .MuiTableBody-root .MuiTableCell-root {
padding: 6px var(--env-var-spacing-2); padding: 6px var(--env-var-spacing-2);
} }
.MuiTable-root .MuiTableBody-root .MuiTableRow-root { .MuiTable-root .MuiTableBody-root .MuiTableRow-root {
height: 50px; height: 50px;
} }
.MuiPaper-root + .MuiPagination-root { .MuiPaper-root + .MuiPagination-root {
border-radius: var(--env-var-radius-1); border-radius: var(--env-var-radius-1);
padding: var(--env-var-spacing-1-plus) var(--env-var-spacing-2); padding: var(--env-var-spacing-1-plus) var(--env-var-spacing-2);
} }
.MuiPaper-root + .MuiPagination-root ul { .MuiPaper-root + .MuiPagination-root ul {
justify-content: center; justify-content: center;
} }
.MuiPaper-root + .MuiPagination-root button { .MuiPaper-root + .MuiPagination-root button {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
font-weight: 500; font-weight: 500;
} }
.MuiPaper-root + .MuiPagination-root ul li:first-child { .MuiPaper-root + .MuiPagination-root ul li:first-child {
margin-right: auto; margin-right: auto;
} }
.MuiPaper-root + .MuiPagination-root ul li:last-child { .MuiPaper-root + .MuiPagination-root ul li:last-child {
margin-left: auto; margin-left: auto;
} }
.MuiPaper-root + .MuiPagination-root ul li:first-child button { .MuiPaper-root + .MuiPagination-root ul li:first-child button {
padding: 0 var(--env-var-spacing-1) 0 var(--env-var-spacing-1-plus); padding: 0 var(--env-var-spacing-1) 0 var(--env-var-spacing-1-plus);
} }
.MuiPaper-root + .MuiPagination-root ul li:last-child button { .MuiPaper-root + .MuiPagination-root ul li:last-child button {
padding: 0 var(--env-var-spacing-1-plus) 0 var(--env-var-spacing-1); padding: 0 var(--env-var-spacing-1-plus) 0 var(--env-var-spacing-1);
} }
.MuiPaper-root + .MuiPagination-root ul li:first-child button::after, .MuiPaper-root + .MuiPagination-root ul li:first-child button::after,
.MuiPaper-root + .MuiPagination-root ul li:last-child button::before { .MuiPaper-root + .MuiPagination-root ul li:last-child button::before {
position: relative; position: relative;
display: inline-block; display: inline-block;
} }
.MuiPaper-root + .MuiPagination-root ul li:first-child button::after { .MuiPaper-root + .MuiPagination-root ul li:first-child button::after {
content: "Previous"; content: "Previous";
margin-left: 15px; margin-left: 15px;
} }
.MuiPaper-root + .MuiPagination-root ul li:last-child button::before { .MuiPaper-root + .MuiPagination-root ul li:last-child button::before {
content: "Next"; content: "Next";
margin-right: 15px; margin-right: 15px;
} }
.MuiPaper-root + .MuiPagination-root div.MuiPaginationItem-root { .MuiPaper-root + .MuiPagination-root div.MuiPaginationItem-root {
user-select: none; user-select: none;
} }
.MuiTablePagination-root p { .MuiTablePagination-root p {
font-weight: 500; font-weight: 500;
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
} }
.MuiTablePagination-root .MuiTablePagination-select.MuiSelect-select { .MuiTablePagination-root .MuiTablePagination-select.MuiSelect-select {
text-align: left; text-align: left;
text-align-last: left; text-align-last: left;
} }
.MuiTablePagination-root button { .MuiTablePagination-root button {
min-width: 0; min-width: 0;
padding: 4px; padding: 4px;
margin-left: 5px; margin-left: 5px;
} }
.MuiTablePagination-root svg { .MuiTablePagination-root svg {
width: 22px; width: 22px;
height: 22px; height: 22px;
} }
.MuiTablePagination-root .MuiSelect-icon { .MuiTablePagination-root .MuiSelect-icon {
width: 16px; width: 16px;
height: 16px; height: 16px;
top: 50%; top: 50%;
right: 8%; right: 8%;
transform: translateY(-50%); transform: translateY(-50%);
} }
.MuiTablePagination-root button.Mui-disabled { .MuiTablePagination-root button.Mui-disabled {
opacity: 0.4; opacity: 0.4;
} }
.table-container .MuiTable-root .MuiTableHead-root .MuiTableCell-root { .table-container .MuiTable-root .MuiTableHead-root .MuiTableCell-root {
text-transform: uppercase; text-transform: uppercase;
opacity: 0.8; opacity: 0.8;
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
font-weight: 400; font-weight: 400;
} }
.monitors .MuiTableCell-root:not(:first-of-type):not(:last-of-type), .monitors .MuiTableCell-root:not(:first-of-type):not(:last-of-type),
.monitors .MuiTableCell-root:not(:first-of-type):not(:last-of-type) { .monitors .MuiTableCell-root:not(:first-of-type):not(:last-of-type) {
padding-left: var(--env-var-spacing-1); padding-left: var(--env-var-spacing-1);
padding-right: var(--env-var-spacing-1); padding-right: var(--env-var-spacing-1);
} }
+221 -220
View File
@@ -2,18 +2,18 @@ import PropTypes from "prop-types";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { import {
TableContainer, TableContainer,
Paper, Paper,
Table, Table,
TableHead, TableHead,
TableRow, TableRow,
TableCell, TableCell,
TableBody, TableBody,
TablePagination, TablePagination,
Box, Box,
Typography, Typography,
Stack, Stack,
Button, Button,
} from "@mui/material"; } from "@mui/material";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { setRowsPerPage } from "../../Features/UI/uiSlice"; import { setRowsPerPage } from "../../Features/UI/uiSlice";
@@ -36,64 +36,64 @@ import "./index.css";
* @returns {JSX.Element} Pagination actions component. * @returns {JSX.Element} Pagination actions component.
*/ */
const TablePaginationActions = (props) => { const TablePaginationActions = (props) => {
const { count, page, rowsPerPage, onPageChange } = props; const { count, page, rowsPerPage, onPageChange } = props;
const handleFirstPageButtonClick = (event) => { const handleFirstPageButtonClick = (event) => {
onPageChange(event, 0); onPageChange(event, 0);
}; };
const handleBackButtonClick = (event) => { const handleBackButtonClick = (event) => {
onPageChange(event, page - 1); onPageChange(event, page - 1);
}; };
const handleNextButtonClick = (event) => { const handleNextButtonClick = (event) => {
onPageChange(event, page + 1); onPageChange(event, page + 1);
}; };
const handleLastPageButtonClick = (event) => { const handleLastPageButtonClick = (event) => {
onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
}; };
return ( return (
<Box sx={{ flexShrink: 0, ml: "24px" }}> <Box sx={{ flexShrink: 0, ml: "24px" }}>
<Button <Button
variant="group" variant="group"
onClick={handleFirstPageButtonClick} onClick={handleFirstPageButtonClick}
disabled={page === 0} disabled={page === 0}
aria-label="first page" aria-label="first page"
> >
<LeftArrowDouble /> <LeftArrowDouble />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleBackButtonClick} onClick={handleBackButtonClick}
disabled={page === 0} disabled={page === 0}
aria-label="previous page" aria-label="previous page"
> >
<LeftArrow /> <LeftArrow />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleNextButtonClick} onClick={handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1} disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="next page" aria-label="next page"
> >
<RightArrow /> <RightArrow />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleLastPageButtonClick} onClick={handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1} disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="last page" aria-label="last page"
> >
<RightArrowDouble /> <RightArrowDouble />
</Button> </Button>
</Box> </Box>
); );
}; };
TablePaginationActions.propTypes = { TablePaginationActions.propTypes = {
count: PropTypes.number.isRequired, count: PropTypes.number.isRequired,
page: PropTypes.number.isRequired, page: PropTypes.number.isRequired,
rowsPerPage: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired,
onPageChange: PropTypes.func.isRequired, onPageChange: PropTypes.func.isRequired,
}; };
/** /**
@@ -150,172 +150,173 @@ TablePaginationActions.propTypes = {
*/ */
const BasicTable = ({ data, paginated, reversed, table }) => { const BasicTable = ({ data, paginated, reversed, table }) => {
const DEFAULT_ROWS_PER_PAGE = 5; const DEFAULT_ROWS_PER_PAGE = 5;
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
const uiState = useSelector((state) => state.ui); const uiState = useSelector((state) => state.ui);
let rowsPerPage = uiState?.[table]?.rowsPerPage ?? DEFAULT_ROWS_PER_PAGE; let rowsPerPage = uiState?.[table]?.rowsPerPage ?? DEFAULT_ROWS_PER_PAGE;
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
useEffect(() => { useEffect(() => {
setPage(0); setPage(0);
}, [data]); }, [data]);
const handleChangePage = (event, newPage) => { const handleChangePage = (event, newPage) => {
setPage(newPage); setPage(newPage);
}; };
const handleChangeRowsPerPage = (event) => { const handleChangeRowsPerPage = (event) => {
dispatch( dispatch(
setRowsPerPage({ setRowsPerPage({
value: parseInt(event.target.value, 10), value: parseInt(event.target.value, 10),
table: table, table: table,
}) })
); );
setPage(0); setPage(0);
}; };
let displayData = []; let displayData = [];
if (data && data.rows) { if (data && data.rows) {
let rows = reversed ? [...data.rows].reverse() : data.rows; let rows = reversed ? [...data.rows].reverse() : data.rows;
displayData = paginated displayData = paginated
? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
: rows; : rows;
} }
if (!data || !data.cols || !data.rows) { if (!data || !data.cols || !data.rows) {
return <div>No data</div>; return <div>No data</div>;
} }
/** /**
* Helper function to calculate the range of displayed rows. * Helper function to calculate the range of displayed rows.
* @returns {string} * @returns {string}
*/ */
const getRange = () => { const getRange = () => {
let start = page * rowsPerPage + 1; let start = page * rowsPerPage + 1;
let end = Math.min(page * rowsPerPage + rowsPerPage, data.rows.length); let end = Math.min(page * rowsPerPage + rowsPerPage, data.rows.length);
return `${start} - ${end}`; return `${start} - ${end}`;
}; };
return ( return (
<> <>
<TableContainer component={Paper}> <TableContainer component={Paper}>
<Table> <Table>
<TableHead> <TableHead>
<TableRow> <TableRow>
{data.cols.map((col) => ( {data.cols.map((col) => (
<TableCell key={col.id}>{col.name}</TableCell> <TableCell key={col.id}>{col.name}</TableCell>
))} ))}
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
{displayData.map((row) => { {displayData.map((row) => {
return ( return (
<TableRow <TableRow
sx={{ sx={{
cursor: row.handleClick ? "pointer" : "default", cursor: row.handleClick ? "pointer" : "default",
"&:hover": { "&:hover": {
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
}, },
}} }}
key={row.id} key={row.id}
onClick={row.handleClick ? row.handleClick : null} onClick={row.handleClick ? row.handleClick : null}
> >
{row.data.map((cell) => { {row.data.map((cell) => {
return <TableCell key={cell.id}>{cell.data}</TableCell>; return <TableCell key={cell.id}>{cell.data}</TableCell>;
})} })}
</TableRow> </TableRow>
); );
})} })}
</TableBody> </TableBody>
</Table> </Table>
</TableContainer> </TableContainer>
{paginated && ( {paginated && (
<Stack <Stack
direction="row" direction="row"
alignItems="center" alignItems="center"
justifyContent="space-between" justifyContent="space-between"
px={theme.spacing(4)} px={theme.spacing(4)}
sx={{ sx={{
"& p": { "& p": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
}} }}
> >
<Typography px={theme.spacing(2)} fontSize={12} sx={{ opacity: 0.7 }}> <Typography
Showing {getRange()} of {data.rows.length} monitor(s) px={theme.spacing(2)}
</Typography> fontSize={12}
<TablePagination sx={{ opacity: 0.7 }}
component="div" >
count={data.rows.length} Showing {getRange()} of {data.rows.length} monitor(s)
page={page} </Typography>
onPageChange={handleChangePage} <TablePagination
rowsPerPage={rowsPerPage} component="div"
rowsPerPageOptions={[5, 10, 15, 25]} count={data.rows.length}
onRowsPerPageChange={handleChangeRowsPerPage} page={page}
ActionsComponent={TablePaginationActions} onPageChange={handleChangePage}
labelRowsPerPage="Rows per page" rowsPerPage={rowsPerPage}
labelDisplayedRows={({ page, count }) => rowsPerPageOptions={[5, 10, 15, 25]}
`Page ${page + 1} of ${Math.max( onRowsPerPageChange={handleChangeRowsPerPage}
0, ActionsComponent={TablePaginationActions}
Math.ceil(count / rowsPerPage) labelRowsPerPage="Rows per page"
)}` labelDisplayedRows={({ page, count }) =>
} `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
slotProps={{ }
select: { slotProps={{
MenuProps: { select: {
keepMounted: true, MenuProps: {
PaperProps: { keepMounted: true,
className: "pagination-dropdown", PaperProps: {
sx: { className: "pagination-dropdown",
mt: 0, sx: {
mb: theme.spacing(2), mt: 0,
}, mb: theme.spacing(2),
}, },
transformOrigin: { vertical: "bottom", horizontal: "left" }, },
anchorOrigin: { vertical: "top", horizontal: "left" }, transformOrigin: { vertical: "bottom", horizontal: "left" },
sx: { mt: theme.spacing(-2) }, anchorOrigin: { vertical: "top", horizontal: "left" },
}, sx: { mt: theme.spacing(-2) },
inputProps: { id: "pagination-dropdown" }, },
IconComponent: SelectorVertical, inputProps: { id: "pagination-dropdown" },
sx: { IconComponent: SelectorVertical,
ml: theme.spacing(4), sx: {
mr: theme.spacing(12), ml: theme.spacing(4),
minWidth: theme.spacing(20), mr: theme.spacing(12),
textAlign: "left", minWidth: theme.spacing(20),
"&.Mui-focused > div": { textAlign: "left",
backgroundColor: theme.palette.background.main, "&.Mui-focused > div": {
}, backgroundColor: theme.palette.background.main,
}, },
}, },
}} },
sx={{ }}
mt: theme.spacing(6), sx={{
color: theme.palette.text.secondary, mt: theme.spacing(6),
"& svg path": { color: theme.palette.text.secondary,
stroke: theme.palette.text.tertiary, "& svg path": {
strokeWidth: 1.3, stroke: theme.palette.text.tertiary,
}, strokeWidth: 1.3,
"& .MuiSelect-select": { },
border: 1, "& .MuiSelect-select": {
borderColor: theme.palette.border.light, border: 1,
borderRadius: theme.shape.borderRadius, borderColor: theme.palette.border.light,
}, borderRadius: theme.shape.borderRadius,
}} },
/> }}
</Stack> />
)} </Stack>
</> )}
); </>
);
}; };
BasicTable.propTypes = { BasicTable.propTypes = {
data: PropTypes.object.isRequired, data: PropTypes.object.isRequired,
paginated: PropTypes.bool, paginated: PropTypes.bool,
reversed: PropTypes.bool, reversed: PropTypes.bool,
rowPerPage: PropTypes.number, rowPerPage: PropTypes.number,
table: PropTypes.string, table: PropTypes.string,
}; };
export default BasicTable; export default BasicTable;
+10 -10
View File
@@ -1,22 +1,22 @@
.MuiBreadcrumbs-root { .MuiBreadcrumbs-root {
height: 34px; height: 34px;
} }
.MuiBreadcrumbs-root svg { .MuiBreadcrumbs-root svg {
width: 16px; width: 16px;
height: 16px; height: 16px;
} }
.MuiBreadcrumbs-root .MuiBreadcrumbs-li a { .MuiBreadcrumbs-root .MuiBreadcrumbs-li a {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
font-weight: 400; font-weight: 400;
} }
.MuiBreadcrumbs-root .MuiBreadcrumbs-li:not(:last-child) { .MuiBreadcrumbs-root .MuiBreadcrumbs-li:not(:last-child) {
cursor: pointer; cursor: pointer;
} }
.MuiBreadcrumbs-root .MuiBreadcrumbs-li:last-child a { .MuiBreadcrumbs-root .MuiBreadcrumbs-li:last-child a {
font-weight: 500; font-weight: 500;
opacity: 1; opacity: 1;
cursor: default; cursor: default;
} }
.MuiBreadcrumbs-root .MuiBreadcrumbs-separator { .MuiBreadcrumbs-root .MuiBreadcrumbs-separator {
margin: 0; margin: 0;
} }
+49 -49
View File
@@ -18,59 +18,59 @@ import "./index.css";
*/ */
const Breadcrumbs = ({ list }) => { const Breadcrumbs = ({ list }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
return ( return (
<MUIBreadcrumbs <MUIBreadcrumbs
separator={<ArrowRight />} separator={<ArrowRight />}
aria-label="breadcrumb" aria-label="breadcrumb"
px={theme.spacing(2)} px={theme.spacing(2)}
py={theme.spacing(3.5)} py={theme.spacing(3.5)}
width="fit-content" width="fit-content"
backgroundColor={theme.palette.background.fill} backgroundColor={theme.palette.background.fill}
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
lineHeight="18px" lineHeight="18px"
sx={{ sx={{
"& .MuiBreadcrumbs-li:not(:last-of-type):hover a": { "& .MuiBreadcrumbs-li:not(:last-of-type):hover a": {
backgroundColor: theme.palette.other.fill, backgroundColor: theme.palette.other.fill,
opacity: 1, opacity: 1,
}, },
}} }}
> >
{list.map((item, index) => { {list.map((item, index) => {
return ( return (
<Box <Box
component="a" component="a"
key={`${item.name}-${index}`} key={`${item.name}-${index}`}
px={theme.spacing(4)} px={theme.spacing(4)}
pt={theme.spacing(2)} pt={theme.spacing(2)}
pb={theme.spacing(3)} pb={theme.spacing(3)}
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
onClick={() => navigate(item.path)} onClick={() => navigate(item.path)}
sx={{ sx={{
opacity: 0.8, opacity: 0.8,
textTransform: "capitalize", textTransform: "capitalize",
"&, &:hover": { "&, &:hover": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
}} }}
> >
{item.name} {item.name}
</Box> </Box>
); );
})} })}
</MUIBreadcrumbs> </MUIBreadcrumbs>
); );
}; };
Breadcrumbs.propTypes = { Breadcrumbs.propTypes = {
list: PropTypes.arrayOf( list: PropTypes.arrayOf(
PropTypes.shape({ PropTypes.shape({
name: PropTypes.string.isRequired, name: PropTypes.string.isRequired,
path: PropTypes.string.isRequired, path: PropTypes.string.isRequired,
}).isRequired }).isRequired
).isRequired, ).isRequired,
}; };
export default Breadcrumbs; export default Breadcrumbs;
+156 -154
View File
@@ -6,164 +6,166 @@ import "./index.css";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
const BarChart = ({ checks = [] }) => { const BarChart = ({ checks = [] }) => {
const theme = useTheme(); const theme = useTheme();
const [animate, setAnimate] = useState(false); const [animate, setAnimate] = useState(false);
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
useEffect(() => { useEffect(() => {
setAnimate(true); setAnimate(true);
}); });
// set responseTime to average if there's only one check // set responseTime to average if there's only one check
if (checks.length === 1) { if (checks.length === 1) {
checks[0] = { ...checks[0], responseTime: 50 }; checks[0] = { ...checks[0], responseTime: 50 };
} }
if (checks.length !== 25) { if (checks.length !== 25) {
const placeholders = Array(25 - checks.length).fill("placeholder"); const placeholders = Array(25 - checks.length).fill("placeholder");
checks = [...checks, ...placeholders]; checks = [...checks, ...placeholders];
} }
return ( return (
<Stack <Stack
direction="row" direction="row"
flexWrap="nowrap" flexWrap="nowrap"
gap={theme.spacing(1.5)} gap={theme.spacing(1.5)}
height="50px" height="50px"
width="fit-content" width="fit-content"
onClick={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()}
sx={{ sx={{
cursor: "default", cursor: "default",
}} }}
> >
{checks.map((check, index) => {checks.map((check, index) =>
check === "placeholder" ? ( check === "placeholder" ? (
<Box <Box
key={`${check}-${index}`} key={`${check}-${index}`}
position="relative" position="relative"
width={theme.spacing(4.5)} width={theme.spacing(4.5)}
height="100%" height="100%"
backgroundColor={theme.palette.background.fill} backgroundColor={theme.palette.background.fill}
sx={{ sx={{
borderRadius: theme.spacing(1.5), borderRadius: theme.spacing(1.5),
}} }}
/> />
) : ( ) : (
<Tooltip <Tooltip
title={ title={
<> <>
<Typography> <Typography>
{formatDateWithTz( {formatDateWithTz(
check.createdAt, check.createdAt,
"ddd, MMMM D, YYYY, HH:mm A", "ddd, MMMM D, YYYY, HH:mm A",
uiTimezone uiTimezone
)} )}
</Typography> </Typography>
<Box mt={theme.spacing(2)}> <Box mt={theme.spacing(2)}>
<Box <Box
display="inline-block" display="inline-block"
width={theme.spacing(4)} width={theme.spacing(4)}
height={theme.spacing(4)} height={theme.spacing(4)}
backgroundColor={ backgroundColor={
check.status check.status ? theme.palette.success.main : theme.palette.error.text
? theme.palette.success.main }
: theme.palette.error.text sx={{ borderRadius: "50%" }}
} />
sx={{ borderRadius: "50%" }} <Stack
/> display="inline-flex"
<Stack direction="row"
display="inline-flex" justifyContent="space-between"
direction="row" ml={theme.spacing(2)}
justifyContent="space-between" gap={theme.spacing(12)}
ml={theme.spacing(2)} >
gap={theme.spacing(12)} <Typography
> component="span"
<Typography component="span" sx={{ opacity: 0.8 }}> sx={{ opacity: 0.8 }}
Response Time >
</Typography> Response Time
<Typography component="span"> </Typography>
{check.originalResponseTime} <Typography component="span">
<Typography component="span" sx={{ opacity: 0.8 }}> {check.originalResponseTime}
{" "} <Typography
ms component="span"
</Typography> sx={{ opacity: 0.8 }}
</Typography> >
</Stack> {" "}
</Box> ms
</> </Typography>
} </Typography>
placement="top" </Stack>
key={`check-${check?._id}`} </Box>
slotProps={{ </>
popper: { }
className: "bar-tooltip", placement="top"
modifiers: [ key={`check-${check?._id}`}
{ slotProps={{
name: "offset", popper: {
options: { className: "bar-tooltip",
offset: [0, -10], modifiers: [
}, {
}, name: "offset",
], options: {
sx: { offset: [0, -10],
"& .MuiTooltip-tooltip": { },
backgroundColor: theme.palette.background.main, },
border: 1, ],
borderColor: theme.palette.border.dark, sx: {
borderRadius: theme.shape.borderRadius, "& .MuiTooltip-tooltip": {
boxShadow: theme.shape.boxShadow, backgroundColor: theme.palette.background.main,
px: theme.spacing(4), border: 1,
py: theme.spacing(2), borderColor: theme.palette.border.dark,
}, borderRadius: theme.shape.borderRadius,
"& .MuiTooltip-tooltip p": { boxShadow: theme.shape.boxShadow,
fontSize: 12, px: theme.spacing(4),
color: theme.palette.text.tertiary, py: theme.spacing(2),
fontWeight: 500, },
}, "& .MuiTooltip-tooltip p": {
"& .MuiTooltip-tooltip span": { fontSize: 12,
fontSize: 11, color: theme.palette.text.tertiary,
color: theme.palette.text.tertiary, fontWeight: 500,
fontWeight: 600, },
}, "& .MuiTooltip-tooltip span": {
}, fontSize: 11,
}, color: theme.palette.text.tertiary,
}} fontWeight: 600,
> },
<Box },
position="relative" },
width="9px" }}
height="100%" >
backgroundColor={ <Box
check.status ? theme.palette.success.bg : theme.palette.error.bg position="relative"
} width="9px"
sx={{ height="100%"
borderRadius: theme.spacing(1.5), backgroundColor={
"&:hover > .MuiBox-root": { check.status ? theme.palette.success.bg : theme.palette.error.bg
filter: "brightness(0.8)", }
}, sx={{
}} borderRadius: theme.spacing(1.5),
> "&:hover > .MuiBox-root": {
<Box filter: "brightness(0.8)",
position="absolute" },
bottom={0} }}
width="100%" >
height={`${animate ? check.responseTime : 0}%`} <Box
backgroundColor={ position="absolute"
check.status bottom={0}
? theme.palette.success.main width="100%"
: theme.palette.error.text height={`${animate ? check.responseTime : 0}%`}
} backgroundColor={
sx={{ check.status ? theme.palette.success.main : theme.palette.error.text
borderRadius: theme.spacing(1.5), }
transition: "height 600ms cubic-bezier(0.4, 0, 0.2, 1)", sx={{
}} borderRadius: theme.spacing(1.5),
/> transition: "height 600ms cubic-bezier(0.4, 0, 0.2, 1)",
</Box> }}
</Tooltip> />
) </Box>
)} </Tooltip>
</Stack> )
); )}
</Stack>
);
}; };
export default BarChart; export default BarChart;
@@ -1,12 +1,12 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import {
AreaChart, AreaChart,
Area, Area,
XAxis, XAxis,
Tooltip, Tooltip,
CartesianGrid, CartesianGrid,
ResponsiveContainer, ResponsiveContainer,
Text, Text,
} from "recharts"; } from "recharts";
import { Box, Stack, Typography } from "@mui/material"; import { Box, Stack, Typography } from "@mui/material";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
@@ -16,181 +16,197 @@ import { formatDateWithTz } from "../../../Utils/timeUtils";
import "./index.css"; import "./index.css";
const CustomToolTip = ({ active, payload, label }) => { const CustomToolTip = ({ active, payload, label }) => {
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
const theme = useTheme(); const theme = useTheme();
if (active && payload && payload.length) { if (active && payload && payload.length) {
return ( return (
<Box <Box
className="area-tooltip" className="area-tooltip"
sx={{ sx={{
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
border: 1, border: 1,
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
py: theme.spacing(2), py: theme.spacing(2),
px: theme.spacing(4), px: theme.spacing(4),
}} }}
> >
<Typography <Typography
sx={{ sx={{
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
fontSize: 12, fontSize: 12,
fontWeight: 500, fontWeight: 500,
}} }}
> >
{formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)} {formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)}
</Typography> </Typography>
<Box mt={theme.spacing(1)}> <Box mt={theme.spacing(1)}>
<Box <Box
display="inline-block" display="inline-block"
width={theme.spacing(4)} width={theme.spacing(4)}
height={theme.spacing(4)} height={theme.spacing(4)}
backgroundColor={theme.palette.primary.main} backgroundColor={theme.palette.primary.main}
sx={{ borderRadius: "50%" }} sx={{ borderRadius: "50%" }}
/> />
<Stack <Stack
display="inline-flex" display="inline-flex"
direction="row" direction="row"
justifyContent="space-between" justifyContent="space-between"
ml={theme.spacing(3)} ml={theme.spacing(3)}
sx={{ sx={{
"& span": { "& span": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
fontSize: 11, fontSize: 11,
fontWeight: 500, fontWeight: 500,
}, },
}} }}
> >
<Typography component="span" sx={{ opacity: 0.8 }}> <Typography
Response Time component="span"
</Typography>{" "} sx={{ opacity: 0.8 }}
<Typography component="span"> >
{payload[0].payload.originalResponseTime} Response Time
<Typography component="span" sx={{ opacity: 0.8 }}> </Typography>{" "}
{" "} <Typography component="span">
ms {payload[0].payload.originalResponseTime}
</Typography> <Typography
</Typography> component="span"
</Stack> sx={{ opacity: 0.8 }}
</Box> >
{/* Display original value */} {" "}
</Box> ms
); </Typography>
} </Typography>
return null; </Stack>
</Box>
{/* Display original value */}
</Box>
);
}
return null;
}; };
const CustomTick = ({ x, y, payload, index }) => { const CustomTick = ({ x, y, payload, index }) => {
const theme = useTheme(); const theme = useTheme();
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
// Render nothing for the first tick // Render nothing for the first tick
if (index === 0) return null; if (index === 0) return null;
return ( return (
<Text <Text
x={x} x={x}
y={y + 10} y={y + 10}
textAnchor="middle" textAnchor="middle"
fill={theme.palette.text.tertiary} fill={theme.palette.text.tertiary}
fontSize={11} fontSize={11}
fontWeight={400} fontWeight={400}
> >
{formatDateWithTz(payload?.value, "h:mm a", uiTimezone)} {formatDateWithTz(payload?.value, "h:mm a", uiTimezone)}
</Text> </Text>
); );
}; };
CustomTick.propTypes = { CustomTick.propTypes = {
x: PropTypes.number, x: PropTypes.number,
y: PropTypes.number, y: PropTypes.number,
payload: PropTypes.object, payload: PropTypes.object,
index: PropTypes.number, index: PropTypes.number,
}; };
const MonitorDetailsAreaChart = ({ checks }) => { const MonitorDetailsAreaChart = ({ checks }) => {
const theme = useTheme(); const theme = useTheme();
const memoizedChecks = useMemo(() => checks, [checks[0]]); const memoizedChecks = useMemo(() => checks, [checks[0]]);
const [isHovered, setIsHovered] = useState(false); const [isHovered, setIsHovered] = useState(false);
return ( return (
<ResponsiveContainer width="100%" minWidth={25} height={220}> <ResponsiveContainer
<AreaChart width="100%"
width="100%" minWidth={25}
height="100%" height={220}
data={memoizedChecks} >
margin={{ <AreaChart
top: 10, width="100%"
right: 0, height="100%"
left: 0, data={memoizedChecks}
bottom: 0, margin={{
}} top: 10,
onMouseMove={() => setIsHovered(true)} right: 0,
onMouseLeave={() => setIsHovered(false)} left: 0,
> bottom: 0,
<CartesianGrid }}
stroke={theme.palette.border.light} onMouseMove={() => setIsHovered(true)}
strokeWidth={1} onMouseLeave={() => setIsHovered(false)}
strokeOpacity={1} >
fill="transparent" <CartesianGrid
vertical={false} stroke={theme.palette.border.light}
/> strokeWidth={1}
<defs> strokeOpacity={1}
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1"> fill="transparent"
<stop vertical={false}
offset="0%" />
stopColor={theme.palette.primary.main} <defs>
stopOpacity={0.8} <linearGradient
/> id="colorUv"
<stop x1="0"
offset="100%" y1="0"
stopColor={theme.palette.primary.light} x2="0"
stopOpacity={0} y2="1"
/> >
</linearGradient> <stop
</defs> offset="0%"
<XAxis stopColor={theme.palette.primary.main}
stroke={theme.palette.border.dark} stopOpacity={0.8}
dataKey="createdAt" />
tick={<CustomTick />} <stop
minTickGap={0} offset="100%"
axisLine={false} stopColor={theme.palette.primary.light}
tickLine={false} stopOpacity={0}
height={20} />
interval="equidistantPreserveStart" </linearGradient>
/> </defs>
<Tooltip <XAxis
cursor={{ stroke: theme.palette.border.light }} stroke={theme.palette.border.dark}
content={<CustomToolTip />} dataKey="createdAt"
wrapperStyle={{ pointerEvents: "none" }} tick={<CustomTick />}
/> minTickGap={0}
<Area axisLine={false}
type="monotone" tickLine={false}
dataKey="responseTime" height={20}
stroke={theme.palette.primary.main} interval="equidistantPreserveStart"
fill="url(#colorUv)" />
strokeWidth={isHovered ? 2.5 : 1.5} <Tooltip
activeDot={{ stroke: theme.palette.background.main, r: 5 }} cursor={{ stroke: theme.palette.border.light }}
/> content={<CustomToolTip />}
</AreaChart> wrapperStyle={{ pointerEvents: "none" }}
</ResponsiveContainer> />
); <Area
type="monotone"
dataKey="responseTime"
stroke={theme.palette.primary.main}
fill="url(#colorUv)"
strokeWidth={isHovered ? 2.5 : 1.5}
activeDot={{ stroke: theme.palette.background.main, r: 5 }}
/>
</AreaChart>
</ResponsiveContainer>
);
}; };
MonitorDetailsAreaChart.propTypes = { MonitorDetailsAreaChart.propTypes = {
checks: PropTypes.array, checks: PropTypes.array,
}; };
CustomToolTip.propTypes = { CustomToolTip.propTypes = {
active: PropTypes.bool, active: PropTypes.bool,
payload: PropTypes.arrayOf( payload: PropTypes.arrayOf(
PropTypes.shape({ PropTypes.shape({
payload: PropTypes.shape({ payload: PropTypes.shape({
originalResponseTime: PropTypes.number.isRequired, originalResponseTime: PropTypes.number.isRequired,
}).isRequired, }).isRequired,
}) })
), ),
label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), label: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}; };
export default MonitorDetailsAreaChart; export default MonitorDetailsAreaChart;
+39 -40
View File
@@ -21,50 +21,49 @@ import { useTheme } from "@emotion/react";
* @returns {React.Element} The `Check` component with a check icon and a label, defined by the `text` prop. * @returns {React.Element} The `Check` component with a check icon and a label, defined by the `text` prop.
*/ */
const Check = ({ text, variant = "info", outlined = false }) => { const Check = ({ text, variant = "info", outlined = false }) => {
const theme = useTheme(); const theme = useTheme();
const colors = { const colors = {
success: theme.palette.success.main, success: theme.palette.success.main,
error: theme.palette.error.text, error: theme.palette.error.text,
info: theme.palette.info.border, info: theme.palette.info.border,
}; };
return ( return (
<Stack <Stack
direction="row" direction="row"
className="check" className="check"
gap={outlined ? theme.spacing(6) : theme.spacing(4)} gap={outlined ? theme.spacing(6) : theme.spacing(4)}
alignItems="center" alignItems="center"
> >
{outlined ? ( {outlined ? (
<CheckOutlined alt="check" /> <CheckOutlined alt="check" />
) : ( ) : (
<Box <Box
lineHeight={0} lineHeight={0}
sx={{ sx={{
"& svg > path": { fill: colors[variant] }, "& svg > path": { fill: colors[variant] },
}} }}
> >
<CheckGrey alt="form checks" /> <CheckGrey alt="form checks" />
</Box> </Box>
)} )}
<Typography <Typography
component="span" component="span"
sx={{ sx={{
color: color: variant === "info" ? theme.palette.text.tertiary : colors[variant],
variant === "info" ? theme.palette.text.tertiary : colors[variant], opacity: 0.8,
opacity: 0.8, }}
}} >
> {text}
{text} </Typography>
</Typography> </Stack>
</Stack> );
);
}; };
Check.propTypes = { Check.propTypes = {
text: PropTypes.oneOfType([PropTypes.string, PropTypes.element]).isRequired, text: PropTypes.oneOfType([PropTypes.string, PropTypes.element]).isRequired,
variant: PropTypes.oneOf(["info", "error", "success"]), variant: PropTypes.oneOf(["info", "error", "success"]),
outlined: PropTypes.bool, outlined: PropTypes.bool,
}; };
export default Check; export default Check;
-1
View File
@@ -1 +0,0 @@
+97 -74
View File
@@ -1,80 +1,103 @@
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { Button, Modal, Stack, Typography } from "@mui/material"; import { Button, Modal, Stack, Typography } from "@mui/material";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
const Dialog = ({ modelTitle, modelDescription, const Dialog = ({
open, onClose, title, confirmationBtnLbl, confirmationBtnOnClick, cancelBtnLbl, cancelBtnOnClick, theme, isLoading, description }) => { modelTitle,
return <Modal modelDescription,
aria-labelledby={modelTitle} open,
aria-describedby={modelDescription} onClose,
open={open} title,
onClose={onClose} > confirmationBtnLbl,
<Stack confirmationBtnOnClick,
gap={theme.spacing(2)} cancelBtnLbl,
sx={{ cancelBtnOnClick,
position: "absolute", theme,
top: "50%", isLoading,
left: "50%", description,
transform: "translate(-50%, -50%)", }) => {
width: 400, return (
bgcolor: theme.palette.background.main, <Modal
border: 1, aria-labelledby={modelTitle}
borderColor: theme.palette.border.light, aria-describedby={modelDescription}
borderRadius: theme.shape.borderRadius, open={open}
boxShadow: 24, onClose={onClose}
p: theme.spacing(15), >
"&:focus": { <Stack
outline: "none", gap={theme.spacing(2)}
}, sx={{
}} position: "absolute",
> top: "50%",
<Typography id={modelTitle} component="h2" left: "50%",
fontSize={16} transform: "translate(-50%, -50%)",
color={theme.palette.text.primary} width: 400,
fontWeight={600}> bgcolor: theme.palette.background.main,
{title} border: 1,
</Typography> borderColor: theme.palette.border.light,
{description && <Typography id={modelDescription} color={theme.palette.text.tertiary}> borderRadius: theme.shape.borderRadius,
{description} boxShadow: 24,
</Typography>} p: theme.spacing(15),
<Stack "&:focus": {
direction="row" outline: "none",
gap={theme.spacing(4)} },
mt={theme.spacing(12)} }}
justifyContent="flex-end" >
> <Typography
<Button id={modelTitle}
variant="text" component="h2"
color="info" fontSize={16}
onClick={cancelBtnOnClick} color={theme.palette.text.primary}
> fontWeight={600}
{cancelBtnLbl} >
</Button> {title}
<LoadingButton </Typography>
variant="contained" {description && (
color="error" <Typography
loading= {isLoading} id={modelDescription}
onClick={confirmationBtnOnClick} color={theme.palette.text.tertiary}
> >
{confirmationBtnLbl} {description}
</LoadingButton> </Typography>
</Stack> )}
</Stack> <Stack
</Modal> direction="row"
} gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={cancelBtnOnClick}
>
{cancelBtnLbl}
</Button>
<LoadingButton
variant="contained"
color="error"
loading={isLoading}
onClick={confirmationBtnOnClick}
>
{confirmationBtnLbl}
</LoadingButton>
</Stack>
</Stack>
</Modal>
);
};
Dialog.propTypes = { Dialog.propTypes = {
modelTitle: PropTypes.string.isRequired, modelTitle: PropTypes.string.isRequired,
modelDescription: PropTypes.string.isRequired, modelDescription: PropTypes.string.isRequired,
open: PropTypes.bool.isRequired, open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired,
title: PropTypes.string.isRequired, title: PropTypes.string.isRequired,
confirmationBtnLbl: PropTypes.string.isRequired, confirmationBtnLbl: PropTypes.string.isRequired,
confirmationBtnOnClick: PropTypes.func.isRequired, confirmationBtnOnClick: PropTypes.func.isRequired,
cancelBtnLbl: PropTypes.string.isRequired, cancelBtnLbl: PropTypes.string.isRequired,
cancelBtnOnClick: PropTypes.func.isRequired, cancelBtnOnClick: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired, theme: PropTypes.object.isRequired,
isLoading: PropTypes.bool.isRequired, isLoading: PropTypes.bool.isRequired,
description: PropTypes.string description: PropTypes.string,
} };
export default Dialog export default Dialog;
+9 -9
View File
@@ -1,24 +1,24 @@
[class*="fallback__"] { [class*="fallback__"] {
width: fit-content; width: fit-content;
margin: auto; margin: auto;
margin-top: 100px; margin-top: 100px;
} }
[class*="fallback__"] h1.MuiTypography-root { [class*="fallback__"] h1.MuiTypography-root {
font-size: var(--env-var-font-size-large); font-size: var(--env-var-font-size-large);
font-weight: 600; font-weight: 600;
} }
[class*="fallback__"] button.MuiButtonBase-root, [class*="fallback__"] button.MuiButtonBase-root,
[class*="fallback__"] .check { [class*="fallback__"] .check {
width: max-content; width: max-content;
} }
[class*="fallback__"] button.MuiButtonBase-root { [class*="fallback__"] button.MuiButtonBase-root {
height: 34px; height: 34px;
} }
[class*="fallback__"] .check span.MuiTypography-root, [class*="fallback__"] .check span.MuiTypography-root,
[class*="fallback__"] button.MuiButtonBase-root { [class*="fallback__"] button.MuiButtonBase-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.fallback__status > .MuiStack-root { .fallback__status > .MuiStack-root {
margin-left: var(--env-var-spacing-2); margin-left: var(--env-var-spacing-2);
} }
+61 -57
View File
@@ -21,67 +21,71 @@ import "./index.css";
*/ */
const Fallback = ({ title, checks, link = "/", isAdmin }) => { const Fallback = ({ title, checks, link = "/", isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const mode = useSelector((state) => state.ui.mode); const mode = useSelector((state) => state.ui.mode);
return ( return (
<Stack <Stack
className={`fallback__${title.trim().split(" ")[0]}`} className={`fallback__${title.trim().split(" ")[0]}`}
alignItems="center" alignItems="center"
gap={theme.spacing(20)} gap={theme.spacing(20)}
> >
{mode === "light" ? ( {mode === "light" ? (
<Skeleton style={{ zIndex: 1 }} /> <Skeleton style={{ zIndex: 1 }} />
) : ( ) : (
<SkeletonDark style={{ zIndex: 1 }} /> <SkeletonDark style={{ zIndex: 1 }} />
)} )}
<Box <Box
className="background-pattern-svg" className="background-pattern-svg"
sx={{ sx={{
"& svg g g:last-of-type path": { "& svg g g:last-of-type path": {
stroke: theme.palette.border.light, stroke: theme.palette.border.light,
}, },
}} }}
> >
<Background style={{ width: "100%" }} /> <Background style={{ width: "100%" }} />
</Box> </Box>
<Stack gap={theme.spacing(4)} maxWidth={"275px"} zIndex={1}> <Stack
<Typography gap={theme.spacing(4)}
component="h1" maxWidth={"275px"}
marginY={theme.spacing(4)} zIndex={1}
color={theme.palette.text.tertiary} >
> <Typography
A {title} is used to: component="h1"
</Typography> marginY={theme.spacing(4)}
{checks.map((check, index) => ( color={theme.palette.text.tertiary}
<Check >
text={check} A {title} is used to:
key={`${title.trim().split(" ")[0]}-${index}`} </Typography>
outlined={true} {checks.map((check, index) => (
/> <Check
))} text={check}
</Stack> key={`${title.trim().split(" ")[0]}-${index}`}
{/* TODO - display a different fallback if user is not an admin*/} outlined={true}
{isAdmin && ( />
<Button ))}
variant="contained" </Stack>
color="primary" {/* TODO - display a different fallback if user is not an admin*/}
sx={{ alignSelf: "center" }} {isAdmin && (
onClick={() => navigate(link)} <Button
> variant="contained"
Let's create your {title} color="primary"
</Button> sx={{ alignSelf: "center" }}
)} onClick={() => navigate(link)}
</Stack> >
); Let's create your {title}
</Button>
)}
</Stack>
);
}; };
Fallback.propTypes = { Fallback.propTypes = {
title: PropTypes.string.isRequired, title: PropTypes.string.isRequired,
checks: PropTypes.arrayOf(PropTypes.string).isRequired, checks: PropTypes.arrayOf(PropTypes.string).isRequired,
link: PropTypes.string, link: PropTypes.string,
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
}; };
export default Fallback; export default Fallback;
+57 -57
View File
@@ -29,68 +29,68 @@ import "./index.css";
*/ */
const Checkbox = ({ const Checkbox = ({
id, id,
label, label,
size = "medium", size = "medium",
isChecked, isChecked,
value, value,
onChange, onChange,
isDisabled, isDisabled,
}) => { }) => {
const sizes = { small: "14px", medium: "16px", large: "18px" }; const sizes = { small: "14px", medium: "16px", large: "18px" };
const theme = useTheme(); const theme = useTheme();
return ( return (
<FormControlLabel <FormControlLabel
className="checkbox-wrapper" className="checkbox-wrapper"
control={ control={
<MuiCheckbox <MuiCheckbox
checked={isDisabled ? false : isChecked} checked={isDisabled ? false : isChecked}
value={value} value={value}
onChange={onChange} onChange={onChange}
icon={<CheckboxOutline />} icon={<CheckboxOutline />}
checkedIcon={<CheckboxFilled />} checkedIcon={<CheckboxFilled />}
inputProps={{ inputProps={{
"aria-label": "controlled checkbox", "aria-label": "controlled checkbox",
id: id, id: id,
}} }}
sx={{ sx={{
"&:hover": { backgroundColor: "transparent" }, "&:hover": { backgroundColor: "transparent" },
"& svg": { width: sizes[size], height: sizes[size] }, "& svg": { width: sizes[size], height: sizes[size] },
}} }}
/> />
} }
label={label} label={label}
disabled={isDisabled} disabled={isDisabled}
sx={{ sx={{
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
p: theme.spacing(2.5), p: theme.spacing(2.5),
m: theme.spacing(-2.5), m: theme.spacing(-2.5),
"& .MuiButtonBase-root": { "& .MuiButtonBase-root": {
width: theme.spacing(10), width: theme.spacing(10),
p: 0, p: 0,
mr: theme.spacing(6), mr: theme.spacing(6),
}, },
"&:not(:has(.Mui-disabled)):hover": { "&:not(:has(.Mui-disabled)):hover": {
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
}, },
"& span.MuiTypography-root": { "& span.MuiTypography-root": {
fontSize: 13, fontSize: 13,
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
}} }}
/> />
); );
}; };
Checkbox.propTypes = { Checkbox.propTypes = {
id: PropTypes.string.isRequired, id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired, label: PropTypes.string.isRequired,
size: PropTypes.oneOf(["small", "medium", "large"]), size: PropTypes.oneOf(["small", "medium", "large"]),
isChecked: PropTypes.bool.isRequired, isChecked: PropTypes.bool.isRequired,
value: PropTypes.string, value: PropTypes.string,
onChange: PropTypes.func, onChange: PropTypes.func,
isDisabled: PropTypes.bool, isDisabled: PropTypes.bool,
}; };
export default Checkbox; export default Checkbox;
+11 -11
View File
@@ -1,31 +1,31 @@
.field { .field {
min-width: 250px; min-width: 250px;
} }
.field h3.MuiTypography-root, .field h3.MuiTypography-root,
.field h5.MuiTypography-root, .field h5.MuiTypography-root,
.field input, .field input,
.field textarea, .field textarea,
.field .input-error { .field .input-error {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.field h5.MuiTypography-root { .field h5.MuiTypography-root {
position: relative; position: relative;
opacity: 0.8; opacity: 0.8;
padding-right: var(--env-var-spacing-1-minus); padding-right: var(--env-var-spacing-1-minus);
} }
.field .MuiInputBase-root:has(input) { .field .MuiInputBase-root:has(input) {
height: 34px; height: 34px;
} }
.field .MuiInputBase-root:has(.MuiInputAdornment-root) { .field .MuiInputBase-root:has(.MuiInputAdornment-root) {
padding-right: var(--env-var-spacing-1-minus); padding-right: var(--env-var-spacing-1-minus);
} }
.field input { .field input {
height: 100%; height: 100%;
padding: 0 var(--env-var-spacing-1-minus); padding: 0 var(--env-var-spacing-1-minus);
} }
.field .MuiInputBase-root:has(textarea) { .field .MuiInputBase-root:has(textarea) {
padding: var(--env-var-spacing-1-minus); padding: var(--env-var-spacing-1-minus);
} }
.register-page .field .MuiOutlinedInput-root fieldset, .register-page .field .MuiOutlinedInput-root fieldset,
@@ -36,5 +36,5 @@
.forgot-password-page .field input, .forgot-password-page .field input,
.set-new-password-page .field .MuiOutlinedInput-root fieldset, .set-new-password-page .field .MuiOutlinedInput-root fieldset,
.set-new-password-page .field input { .set-new-password-page .field input {
border-radius: var(--env-var-radius-2); border-radius: var(--env-var-radius-2);
} }
+187 -202
View File
@@ -1,13 +1,7 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { forwardRef, useState } from "react"; import { forwardRef, useState } from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { import { IconButton, InputAdornment, Stack, TextField, Typography } from "@mui/material";
IconButton,
InputAdornment,
Stack,
TextField,
Typography,
} from "@mui/material";
import VisibilityOff from "@mui/icons-material/VisibilityOff"; import VisibilityOff from "@mui/icons-material/VisibilityOff";
import Visibility from "@mui/icons-material/Visibility"; import Visibility from "@mui/icons-material/Visibility";
import "./index.css"; import "./index.css";
@@ -33,208 +27,199 @@ import "./index.css";
*/ */
const Field = forwardRef( const Field = forwardRef(
( (
{ {
type = "text", type = "text",
id, id,
name, name,
label, label,
https, https,
isRequired, isRequired,
isOptional, isOptional,
optionalLabel, optionalLabel,
autoComplete, autoComplete,
placeholder, placeholder,
value, value,
onChange, onChange,
onInput, onInput,
error, error,
disabled, disabled,
hidden, hidden,
}, },
ref ref
) => { ) => {
const theme = useTheme(); const theme = useTheme();
const [isVisible, setVisible] = useState(false); const [isVisible, setVisible] = useState(false);
return ( return (
<Stack <Stack
gap={theme.spacing(2)} gap={theme.spacing(2)}
className={`field field-${type}`} className={`field field-${type}`}
sx={{ sx={{
"& fieldset": { "& fieldset": {
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
}, },
"&:not(:has(.Mui-disabled)):not(:has(.input-error)) .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset": "&:not(:has(.Mui-disabled)):not(:has(.input-error)) .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset":
{ {
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
}, },
"&:has(.input-error) .MuiOutlinedInput-root fieldset": { "&:has(.input-error) .MuiOutlinedInput-root fieldset": {
borderColor: theme.palette.error.text, borderColor: theme.palette.error.text,
}, },
display: hidden ? "none" : "", display: hidden ? "none" : "",
}} }}
> >
{label && ( {label && (
<Typography <Typography
component="h3" component="h3"
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
fontWeight={500} fontWeight={500}
> >
{label} {label}
{isRequired ? ( {isRequired ? (
<Typography <Typography
component="span" component="span"
ml={theme.spacing(1)} ml={theme.spacing(1)}
color={theme.palette.error.text} color={theme.palette.error.text}
> >
* *
</Typography> </Typography>
) : ( ) : (
"" ""
)} )}
{isOptional ? ( {isOptional ? (
<Typography <Typography
component="span" component="span"
fontSize="inherit" fontSize="inherit"
fontWeight={400} fontWeight={400}
ml={theme.spacing(2)} ml={theme.spacing(2)}
sx={{ opacity: 0.6 }} sx={{ opacity: 0.6 }}
> >
{optionalLabel || "(optional)"} {optionalLabel || "(optional)"}
</Typography> </Typography>
) : ( ) : (
"" ""
)} )}
</Typography> </Typography>
)} )}
<TextField <TextField
type={type === "password" ? (isVisible ? "text" : type) : type} type={type === "password" ? (isVisible ? "text" : type) : type}
name={name} name={name}
id={id} id={id}
autoComplete={autoComplete} autoComplete={autoComplete}
placeholder={placeholder} placeholder={placeholder}
multiline={type === "description"} multiline={type === "description"}
rows={type === "description" ? 4 : 1} rows={type === "description" ? 4 : 1}
value={value} value={value}
onInput={onInput} onInput={onInput}
onChange={onChange} onChange={onChange}
disabled={disabled} disabled={disabled}
inputRef={ref} inputRef={ref}
inputProps={{ inputProps={{
sx: { sx: {
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
"&:-webkit-autofill": { "&:-webkit-autofill": {
WebkitBoxShadow: `0 0 0 100px ${theme.palette.other.autofill} inset`, WebkitBoxShadow: `0 0 0 100px ${theme.palette.other.autofill} inset`,
WebkitTextFillColor: theme.palette.text.secondary, WebkitTextFillColor: theme.palette.text.secondary,
borderRadius: "0 5px 5px 0", borderRadius: "0 5px 5px 0",
}, },
}, },
}} }}
sx={ sx={
type === "url" type === "url"
? { ? {
"& .MuiInputBase-root": { padding: 0 }, "& .MuiInputBase-root": { padding: 0 },
"& .MuiStack-root": { "& .MuiStack-root": {
borderTopLeftRadius: theme.shape.borderRadius, borderTopLeftRadius: theme.shape.borderRadius,
borderBottomLeftRadius: theme.shape.borderRadius, borderBottomLeftRadius: theme.shape.borderRadius,
}, },
} }
: { : {}
}
} InputProps={{
} startAdornment: type === "url" && (
InputProps={{ <Stack
startAdornment: type === "url" && ( direction="row"
<Stack alignItems="center"
direction="row" height="100%"
alignItems="center" sx={{
height="100%" borderRight: `solid 1px ${theme.palette.border.dark}`,
sx={{ backgroundColor: theme.palette.background.accent,
borderRight: `solid 1px ${theme.palette.border.dark}`, pl: theme.spacing(6),
backgroundColor: theme.palette.background.accent, }}
pl: theme.spacing(6), >
}} <Typography
> component="h5"
<Typography color={theme.palette.text.secondary}
component="h5" sx={{ lineHeight: 1 }}
color={theme.palette.text.secondary} >
sx={{ lineHeight: 1 }} {https ? "https" : "http"}://
> </Typography>
{https ? "https" : "http"}:// </Stack>
</Typography> ),
</Stack> endAdornment: type === "password" && (
), <InputAdornment position="end">
endAdornment: type === "password" && ( <IconButton
<InputAdornment position="end"> aria-label="toggle password visibility"
<IconButton onClick={() => setVisible((show) => !show)}
aria-label="toggle password visibility" tabIndex={-1}
onClick={() => setVisible((show) => !show)} sx={{
tabIndex={-1} color: theme.palette.border.dark,
sx={{ padding: theme.spacing(1),
color: theme.palette.border.dark, "&:focus": {
padding: theme.spacing(1), outline: "none",
"&:focus": { },
outline: "none", "& .MuiTouchRipple-root": {
}, pointerEvents: "none",
"& .MuiTouchRipple-root": { display: "none",
pointerEvents: "none", },
display: "none", }}
}, >
}} {!isVisible ? <VisibilityOff /> : <Visibility />}
> </IconButton>
{!isVisible ? <VisibilityOff /> : <Visibility />} </InputAdornment>
</IconButton> ),
</InputAdornment> }}
), />
}} {error && (
/> <Typography
{error && ( component="span"
<Typography className="input-error"
component="span" color={theme.palette.error.text}
className="input-error" mt={theme.spacing(2)}
color={theme.palette.error.text} sx={{
mt={theme.spacing(2)} opacity: 0.8,
sx={{ }}
opacity: 0.8, >
}} {error}
> </Typography>
{error} )}
</Typography> </Stack>
)} );
</Stack> }
);
}
); );
Field.displayName = "Field"; Field.displayName = "Field";
Field.propTypes = { Field.propTypes = {
type: PropTypes.oneOf([ type: PropTypes.oneOf(["text", "password", "url", "email", "description", "number"]),
"text", id: PropTypes.string.isRequired,
"password", name: PropTypes.string,
"url", label: PropTypes.string,
"email", https: PropTypes.bool,
"description", isRequired: PropTypes.bool,
"number", isOptional: PropTypes.bool,
]), optionalLabel: PropTypes.string,
id: PropTypes.string.isRequired, autoComplete: PropTypes.string,
name: PropTypes.string, placeholder: PropTypes.string,
label: PropTypes.string, value: PropTypes.string.isRequired,
https: PropTypes.bool, onChange: PropTypes.func,
isRequired: PropTypes.bool, onInput: PropTypes.func,
isOptional: PropTypes.bool, error: PropTypes.string,
optionalLabel: PropTypes.string, disabled: PropTypes.bool,
autoComplete: PropTypes.string, hidden: PropTypes.bool,
placeholder: PropTypes.string,
value: PropTypes.string.isRequired,
onChange: PropTypes.func,
onInput: PropTypes.func,
error: PropTypes.string,
disabled: PropTypes.bool,
hidden: PropTypes.bool,
}; };
export default Field; export default Field;
+5 -5
View File
@@ -1,18 +1,18 @@
.MuiStack-root:has(#modal-update-picture) h1.MuiTypography-root { .MuiStack-root:has(#modal-update-picture) h1.MuiTypography-root {
font-weight: 600; font-weight: 600;
} }
.image-field-wrapper h2.MuiTypography-root, .image-field-wrapper h2.MuiTypography-root,
.MuiStack-root:has(#modal-update-picture) button, .MuiStack-root:has(#modal-update-picture) button,
.MuiStack-root:has(#modal-update-picture) h1.MuiTypography-root { .MuiStack-root:has(#modal-update-picture) h1.MuiTypography-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.image-field-wrapper h2.MuiTypography-root { .image-field-wrapper h2.MuiTypography-root {
margin-top: 10px; margin-top: 10px;
} }
.image-field-wrapper + p.MuiTypography-root { .image-field-wrapper + p.MuiTypography-root {
margin-top: 8px; margin-top: 8px;
} }
.image-field-wrapper + p.MuiTypography-root, .image-field-wrapper + p.MuiTypography-root,
.image-field-wrapper p.MuiTypography-root { .image-field-wrapper p.MuiTypography-root {
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
} }
+128 -122
View File
@@ -15,133 +15,139 @@ import { checkImage } from "../../../Utils/fileUtils";
*/ */
const ImageField = ({ id, src, loading, onChange }) => { const ImageField = ({ id, src, loading, onChange }) => {
const theme = useTheme(); const theme = useTheme();
const [isDragging, setIsDragging] = useState(false); const [isDragging, setIsDragging] = useState(false);
const handleDragEnter = () => { const handleDragEnter = () => {
setIsDragging(true); setIsDragging(true);
}; };
const handleDragLeave = () => { const handleDragLeave = () => {
setIsDragging(false); setIsDragging(false);
}; };
return ( return (
<> <>
{!checkImage(src) || loading ? ( {!checkImage(src) || loading ? (
<> <>
<Box <Box
className="image-field-wrapper" className="image-field-wrapper"
mt={theme.spacing(8)} mt={theme.spacing(8)}
sx={{ sx={{
position: "relative", position: "relative",
height: "fit-content", height: "fit-content",
border: "dashed", border: "dashed",
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
borderColor: isDragging borderColor: isDragging
? theme.palette.primary.main ? theme.palette.primary.main
: theme.palette.border.light, : theme.palette.border.light,
borderWidth: "2px", borderWidth: "2px",
transition: "0.2s", transition: "0.2s",
"&:hover": { "&:hover": {
borderColor: theme.palette.primary.main, borderColor: theme.palette.primary.main,
backgroundColor: "hsl(215, 87%, 51%, 0.05)", backgroundColor: "hsl(215, 87%, 51%, 0.05)",
}, },
}} }}
onDragEnter={handleDragEnter} onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave} onDragLeave={handleDragLeave}
onDrop={handleDragLeave} onDrop={handleDragLeave}
> >
<TextField <TextField
id={id} id={id}
type="file" type="file"
onChange={onChange} onChange={onChange}
sx={{ sx={{
width: "100%", width: "100%",
"& .MuiInputBase-input[type='file']": { "& .MuiInputBase-input[type='file']": {
opacity: 0, opacity: 0,
cursor: "pointer", cursor: "pointer",
maxWidth: "500px", maxWidth: "500px",
minHeight: "175px", minHeight: "175px",
}, },
"& fieldset": { "& fieldset": {
padding: 0, padding: 0,
border: "none", border: "none",
}, },
}} }}
/> />
<Stack <Stack
className="custom-file-text" className="custom-file-text"
alignItems="center" alignItems="center"
gap="4px" gap="4px"
sx={{ sx={{
position: "absolute", position: "absolute",
top: "50%", top: "50%",
left: "50%", left: "50%",
transform: "translate(-50%, -50%)", transform: "translate(-50%, -50%)",
zIndex: "-1", zIndex: "-1",
width: "100%", width: "100%",
}} }}
> >
<IconButton <IconButton
sx={{ sx={{
pointerEvents: "none", pointerEvents: "none",
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
border: `solid ${theme.shape.borderThick}px ${theme.palette.border.light}`, border: `solid ${theme.shape.borderThick}px ${theme.palette.border.light}`,
boxShadow: theme.shape.boxShadow, boxShadow: theme.shape.boxShadow,
}} }}
> >
<CloudUploadIcon /> <CloudUploadIcon />
</IconButton> </IconButton>
<Typography component="h2" color={theme.palette.text.tertiary}> <Typography
<Typography component="h2"
component="span" color={theme.palette.text.tertiary}
fontSize="inherit" >
color={theme.palette.primary.main} <Typography
fontWeight={500} component="span"
> fontSize="inherit"
Click to upload color={theme.palette.primary.main}
</Typography>{" "} fontWeight={500}
or drag and drop >
</Typography> Click to upload
<Typography </Typography>{" "}
component="p" or drag and drop
color={theme.palette.text.tertiary} </Typography>
sx={{ opacity: 0.6 }} <Typography
> component="p"
(maximum size: 3MB) color={theme.palette.text.tertiary}
</Typography> sx={{ opacity: 0.6 }}
</Stack> >
</Box> (maximum size: 3MB)
<Typography </Typography>
component="p" </Stack>
color={theme.palette.text.tertiary} </Box>
sx={{ opacity: 0.6 }} <Typography
> component="p"
Supported formats: JPG, PNG color={theme.palette.text.tertiary}
</Typography> sx={{ opacity: 0.6 }}
</> >
) : ( Supported formats: JPG, PNG
<Stack direction="row" justifyContent="center"> </Typography>
<Box </>
sx={{ ) : (
width: "250px", <Stack
height: "250px", direction="row"
borderRadius: "50%", justifyContent="center"
overflow: "hidden", >
backgroundImage: `url(${src})`, <Box
backgroundSize: "cover", sx={{
}} width: "250px",
></Box> height: "250px",
</Stack> borderRadius: "50%",
)} overflow: "hidden",
</> backgroundImage: `url(${src})`,
); backgroundSize: "cover",
}}
></Box>
</Stack>
)}
</>
);
}; };
ImageField.propTypes = { ImageField.propTypes = {
id: PropTypes.string.isRequired, id: PropTypes.string.isRequired,
src: PropTypes.string, src: PropTypes.string,
onChange: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired,
}; };
export default ImageField; export default ImageField;
@@ -1 +0,0 @@
+52 -52
View File
@@ -25,62 +25,62 @@ import "./index.css";
*/ */
const Radio = (props) => { const Radio = (props) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<FormControlLabel <FormControlLabel
className="custom-radio-button" className="custom-radio-button"
checked={props.checked} checked={props.checked}
value={props.value} value={props.value}
control={ control={
<MUIRadio <MUIRadio
id={props.id} id={props.id}
size={props.size} size={props.size}
checkedIcon={<RadioChecked />} checkedIcon={<RadioChecked />}
sx={{ sx={{
color: "transparent", color: "transparent",
width: 16, width: 16,
height: 16, height: 16,
boxShadow: "inset 0 0 0 1px #656a74", boxShadow: "inset 0 0 0 1px #656a74",
mt: theme.spacing(0.5), mt: theme.spacing(0.5),
}} }}
/> />
} }
onChange={props.onChange} onChange={props.onChange}
label={ label={
<> <>
<Typography component="p">{props.title}</Typography> <Typography component="p">{props.title}</Typography>
<Typography <Typography
component="h6" component="h6"
mt={theme.spacing(1)} mt={theme.spacing(1)}
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
> >
{props.desc} {props.desc}
</Typography> </Typography>
</> </>
} }
labelPlacement="end" labelPlacement="end"
sx={{ sx={{
alignItems: "flex-start", alignItems: "flex-start",
p: theme.spacing(2.5), p: theme.spacing(2.5),
m: theme.spacing(-2.5), m: theme.spacing(-2.5),
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
"&:hover": { "&:hover": {
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
}, },
"& .MuiButtonBase-root": { "& .MuiButtonBase-root": {
p: 0, p: 0,
mr: theme.spacing(6), mr: theme.spacing(6),
}, },
}} }}
/> />
); );
}; };
Radio.propTypes = { Radio.propTypes = {
title: PropTypes.string.isRequired, title: PropTypes.string.isRequired,
desc: PropTypes.string, desc: PropTypes.string,
size: PropTypes.string, size: PropTypes.string,
}; };
export default Radio; export default Radio;
+157 -165
View File
@@ -1,12 +1,5 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import { Box, ListItem, Autocomplete, TextField, Stack, Typography } from "@mui/material";
Box,
ListItem,
Autocomplete,
TextField,
Stack,
Typography,
} from "@mui/material";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import SearchIcon from "../../../assets/icons/search.svg?react"; import SearchIcon from "../../../assets/icons/search.svg?react";
@@ -24,172 +17,171 @@ import SearchIcon from "../../../assets/icons/search.svg?react";
*/ */
const SearchAdornment = () => { const SearchAdornment = () => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Box <Box
mr={theme.spacing(4)} mr={theme.spacing(4)}
height={16} height={16}
sx={{ sx={{
"& svg": { "& svg": {
width: 16, width: 16,
height: 16, height: 16,
"& path": { "& path": {
stroke: theme.palette.text.tertiary, stroke: theme.palette.text.tertiary,
strokeWidth: 1.2, strokeWidth: 1.2,
}, },
}, },
}} }}
> >
<SearchIcon /> <SearchIcon />
</Box> </Box>
); );
}; };
const Search = ({ const Search = ({
id, id,
options, options,
filteredBy, filteredBy,
secondaryLabel, secondaryLabel,
value, value,
inputValue, inputValue,
handleInputChange, handleInputChange,
handleChange, handleChange,
sx, sx,
multiple = false, multiple = false,
isAdorned = true, isAdorned = true,
error, error,
disabled, disabled,
}) => { }) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Autocomplete <Autocomplete
multiple={multiple} multiple={multiple}
id={id} id={id}
value={value} value={value}
inputValue={inputValue} inputValue={inputValue}
onInputChange={(_, newValue) => { onInputChange={(_, newValue) => {
handleInputChange(newValue); handleInputChange(newValue);
}} }}
onChange={(_, newValue) => { onChange={(_, newValue) => {
handleChange && handleChange(newValue); handleChange && handleChange(newValue);
}} }}
fullWidth fullWidth
freeSolo freeSolo
disabled={disabled} disabled={disabled}
disableClearable disableClearable
options={options} options={options}
getOptionLabel={(option) => option[filteredBy]} getOptionLabel={(option) => option[filteredBy]}
renderInput={(params) => ( renderInput={(params) => (
<Stack> <Stack>
<TextField <TextField
{...params} {...params}
error={Boolean(error)} error={Boolean(error)}
placeholder="Type to search" placeholder="Type to search"
InputProps={{ InputProps={{
...params.InputProps, ...params.InputProps,
...(isAdorned && { startAdornment: <SearchAdornment /> }), ...(isAdorned && { startAdornment: <SearchAdornment /> }),
}} }}
sx={{ sx={{
"& fieldset": { "& fieldset": {
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
}, },
"& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset": "& .MuiOutlinedInput-root:hover:not(:has(input:focus)):not(:has(textarea:focus)) fieldset":
{ {
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
}, },
}} }}
/> />
{error && ( {error && (
<Typography <Typography
component="span" component="span"
className="input-error" className="input-error"
color={theme.palette.error.text} color={theme.palette.error.text}
mt={theme.spacing(2)} mt={theme.spacing(2)}
sx={{ sx={{
opacity: 0.8, opacity: 0.8,
}} }}
> >
{error} {error}
</Typography> </Typography>
)} )}
</Stack> </Stack>
)} )}
filterOptions={(options, { inputValue }) => { filterOptions={(options, { inputValue }) => {
const filtered = options.filter((option) => const filtered = options.filter((option) =>
option[filteredBy].toLowerCase().includes(inputValue.toLowerCase()) option[filteredBy].toLowerCase().includes(inputValue.toLowerCase())
); );
if (filtered.length === 0) { if (filtered.length === 0) {
return [{ [filteredBy]: "No monitors found", noOptions: true }]; return [{ [filteredBy]: "No monitors found", noOptions: true }];
} }
return filtered; return filtered;
}} }}
renderOption={(props, option) => { renderOption={(props, option) => {
const { key, ...optionProps } = props; const { key, ...optionProps } = props;
return ( return (
<ListItem <ListItem
key={key} key={key}
{...optionProps} {...optionProps}
sx={ sx={
option.noOptions option.noOptions
? { ? {
pointerEvents: "none", pointerEvents: "none",
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
} }
: {} : {}
} }
> >
{option[filteredBy] + {option[filteredBy] + (secondaryLabel ? ` (${option[secondaryLabel]})` : "")}
(secondaryLabel ? ` (${option[secondaryLabel]})` : "")} </ListItem>
</ListItem> );
); }}
}} slotProps={{
slotProps={{ popper: {
popper: { keepMounted: true,
keepMounted: true, sx: {
sx: { "& ul": { p: 2 },
"& ul": { p: 2 }, "& li.MuiAutocomplete-option": {
"& li.MuiAutocomplete-option": { color: theme.palette.text.secondary,
color: theme.palette.text.secondary, px: 4,
px: 4, borderRadius: theme.shape.borderRadius,
borderRadius: theme.shape.borderRadius, },
}, "& .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'], & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'].Mui-focused, & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true']:hover":
"& .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'], & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true'].Mui-focused, & .MuiAutocomplete-listbox .MuiAutocomplete-option[aria-selected='true']:hover": {
{ backgroundColor: theme.palette.background.fill,
backgroundColor: theme.palette.background.fill, },
}, "& .MuiAutocomplete-noOptions": {
"& .MuiAutocomplete-noOptions": { px: theme.spacing(6),
px: theme.spacing(6), py: theme.spacing(5),
py: theme.spacing(5), },
}, },
}, },
}, }}
}} sx={{
sx={{ height: 34,
height: 34, "&.MuiAutocomplete-root .MuiAutocomplete-input": { p: 0 },
"&.MuiAutocomplete-root .MuiAutocomplete-input": { p: 0 }, ...sx,
...sx, }}
}} />
/> );
);
}; };
Search.propTypes = { Search.propTypes = {
id: PropTypes.string, id: PropTypes.string,
multiple: PropTypes.bool, multiple: PropTypes.bool,
options: PropTypes.array.isRequired, options: PropTypes.array.isRequired,
filteredBy: PropTypes.string.isRequired, filteredBy: PropTypes.string.isRequired,
secondaryLabel: PropTypes.string, secondaryLabel: PropTypes.string,
value: PropTypes.array, value: PropTypes.array,
inputValue: PropTypes.string.isRequired, inputValue: PropTypes.string.isRequired,
handleInputChange: PropTypes.func.isRequired, handleInputChange: PropTypes.func.isRequired,
handleChange: PropTypes.func, handleChange: PropTypes.func,
isAdorned: PropTypes.bool, isAdorned: PropTypes.bool,
sx: PropTypes.object, sx: PropTypes.object,
error: PropTypes.string, error: PropTypes.string,
disabled: PropTypes.bool, disabled: PropTypes.bool,
}; };
export default Search; export default Search;
@@ -1,7 +1,7 @@
.select-wrapper .select-component > .MuiSelect-select { .select-wrapper .select-component > .MuiSelect-select {
padding: 0 10px; padding: 0 10px;
height: 34px; height: 34px;
display: flex; display: flex;
align-items: center; align-items: center;
line-height: 1; line-height: 1;
} }
+98 -100
View File
@@ -1,11 +1,6 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { import { MenuItem, Select as MuiSelect, Stack, Typography } from "@mui/material";
MenuItem,
Select as MuiSelect,
Stack,
Typography,
} from "@mui/material";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"; import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import "./index.css"; import "./index.css";
@@ -44,105 +39,108 @@ import "./index.css";
*/ */
const Select = ({ const Select = ({
id, id,
label, label,
placeholder, placeholder,
isHidden, isHidden,
value, value,
items, items,
onChange, onChange,
sx, sx,
name = "", name = "",
}) => { }) => {
const theme = useTheme(); const theme = useTheme();
const itemStyles = { const itemStyles = {
fontSize: "var(--env-var-font-size-medium)", fontSize: "var(--env-var-font-size-medium)",
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
margin: theme.spacing(2), margin: theme.spacing(2),
}; };
return ( return (
<Stack gap={theme.spacing(2)} className="select-wrapper"> <Stack
{label && ( gap={theme.spacing(2)}
<Typography className="select-wrapper"
component="h3" >
color={theme.palette.text.secondary} {label && (
fontWeight={500} <Typography
fontSize={13} component="h3"
> color={theme.palette.text.secondary}
{label} fontWeight={500}
</Typography> fontSize={13}
)} >
<MuiSelect {label}
className="select-component" </Typography>
value={value} )}
onChange={onChange} <MuiSelect
displayEmpty className="select-component"
name={name} value={value}
inputProps={{ id: id }} onChange={onChange}
IconComponent={KeyboardArrowDownIcon} displayEmpty
MenuProps={{ disableScrollLock: true }} name={name}
sx={{ inputProps={{ id: id }}
fontSize: 13, IconComponent={KeyboardArrowDownIcon}
minWidth: "125px", MenuProps={{ disableScrollLock: true }}
"& fieldset": { sx={{
borderRadius: theme.shape.borderRadius, fontSize: 13,
borderColor: theme.palette.border.dark, minWidth: "125px",
}, "& fieldset": {
"&:not(.Mui-focused):hover fieldset": { borderRadius: theme.shape.borderRadius,
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
}, },
"& svg path": { "&:not(.Mui-focused):hover fieldset": {
fill: theme.palette.other.icon, borderColor: theme.palette.border.dark,
}, },
...sx, "& svg path": {
}} fill: theme.palette.other.icon,
> },
{placeholder && ( ...sx,
<MenuItem }}
className="select-placeholder" >
value="0" {placeholder && (
sx={{ <MenuItem
display: isHidden ? "none" : "flex", className="select-placeholder"
visibility: isHidden ? "none" : "visible", value="0"
...itemStyles, sx={{
}} display: isHidden ? "none" : "flex",
> visibility: isHidden ? "none" : "visible",
{placeholder} ...itemStyles,
</MenuItem> }}
)} >
{items.map((item) => ( {placeholder}
<MenuItem </MenuItem>
value={item._id} )}
key={`${id}-${item._id}`} {items.map((item) => (
sx={{ <MenuItem
...itemStyles, value={item._id}
}} key={`${id}-${item._id}`}
> sx={{
{item.name} ...itemStyles,
</MenuItem> }}
))} >
</MuiSelect> {item.name}
</Stack> </MenuItem>
); ))}
</MuiSelect>
</Stack>
);
}; };
Select.propTypes = { Select.propTypes = {
id: PropTypes.string.isRequired, id: PropTypes.string.isRequired,
name: PropTypes.string, name: PropTypes.string,
label: PropTypes.string, label: PropTypes.string,
placeholder: PropTypes.string, placeholder: PropTypes.string,
isHidden: PropTypes.bool, isHidden: PropTypes.bool,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
items: PropTypes.arrayOf( items: PropTypes.arrayOf(
PropTypes.shape({ PropTypes.shape({
_id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, _id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
name: PropTypes.string.isRequired, name: PropTypes.string.isRequired,
}) })
).isRequired, ).isRequired,
onChange: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired,
sx: PropTypes.object, sx: PropTypes.object,
}; };
export default Select; export default Select;
+5 -5
View File
@@ -1,7 +1,7 @@
.label { .label {
border: 1px solid #000; border: 1px solid #000;
display: inline-flex; display: inline-flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
line-height: normal; line-height: normal;
} }
+109 -118
View File
@@ -20,56 +20,56 @@ import "./index.css";
*/ */
const BaseLabel = ({ label, styles, children }) => { const BaseLabel = ({ label, styles, children }) => {
const theme = useTheme(); const theme = useTheme();
// Grab the default borderRadius from the theme to match button style // Grab the default borderRadius from the theme to match button style
const { borderRadius } = theme.shape; const { borderRadius } = theme.shape;
// Calculate padding for the label to mimic button. Appears to scale correctly, not 100% sure though. // Calculate padding for the label to mimic button. Appears to scale correctly, not 100% sure though.
const padding = theme.spacing(1 * 0.75, 2); const padding = theme.spacing(1 * 0.75, 2);
return ( return (
<Box <Box
className="label" className="label"
sx={{ sx={{
borderRadius: borderRadius, borderRadius: borderRadius,
borderColor: theme.palette.text.tertiary, borderColor: theme.palette.text.tertiary,
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
padding: padding, padding: padding,
...styles, ...styles,
}} }}
> >
{children} {children}
{label} {label}
</Box> </Box>
); );
}; };
BaseLabel.propTypes = { BaseLabel.propTypes = {
label: PropTypes.string.isRequired, label: PropTypes.string.isRequired,
styles: PropTypes.shape({ styles: PropTypes.shape({
color: PropTypes.string, color: PropTypes.string,
backgroundColor: PropTypes.string, backgroundColor: PropTypes.string,
}), }),
children: PropTypes.node, children: PropTypes.node,
}; };
// Produces a lighter color based on a hex color and a percent // Produces a lighter color based on a hex color and a percent
// lightenColor("#067647", 20) will produce a color 20% lighter than #067647 // lightenColor("#067647", 20) will produce a color 20% lighter than #067647
const lightenColor = (color, percent) => { const lightenColor = (color, percent) => {
let r = parseInt(color.substring(1, 3), 16); let r = parseInt(color.substring(1, 3), 16);
let g = parseInt(color.substring(3, 5), 16); let g = parseInt(color.substring(3, 5), 16);
let b = parseInt(color.substring(5, 7), 16); let b = parseInt(color.substring(5, 7), 16);
const amt = Math.round((255 * percent) / 100); const amt = Math.round((255 * percent) / 100);
r = r + amt <= 255 ? r + amt : 255; r = r + amt <= 255 ? r + amt : 255;
g = g + amt <= 255 ? g + amt : 255; g = g + amt <= 255 ? g + amt : 255;
b = b + amt <= 255 ? b + amt : 255; b = b + amt <= 255 ? b + amt : 255;
r = r.toString(16).padStart(2, "0"); r = r.toString(16).padStart(2, "0");
g = g.toString(16).padStart(2, "0"); g = g.toString(16).padStart(2, "0");
b = b.toString(16).padStart(2, "0"); b = b.toString(16).padStart(2, "0");
return `#${r}${g}${b}`; return `#${r}${g}${b}`;
}; };
/** /**
@@ -84,34 +84,31 @@ const lightenColor = (color, percent) => {
*/ */
const ColoredLabel = ({ label, color }) => { const ColoredLabel = ({ label, color }) => {
const theme = useTheme(); const theme = useTheme();
// If an invalid color is passed, default to the labelGray color // If an invalid color is passed, default to the labelGray color
if ( if (typeof color !== "string" || !/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color)) {
typeof color !== "string" || color = theme.palette.border.light;
!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(color) }
) {
color = theme.palette.border.light;
}
// Calculate lighter shades for border and bg // Calculate lighter shades for border and bg
const borderColor = lightenColor(color, 20); const borderColor = lightenColor(color, 20);
const bgColor = lightenColor(color, 75); const bgColor = lightenColor(color, 75);
return ( return (
<BaseLabel <BaseLabel
label={label} label={label}
styles={{ styles={{
color: color, color: color,
borderColor: borderColor, borderColor: borderColor,
backgroundColor: bgColor, backgroundColor: bgColor,
}} }}
></BaseLabel> ></BaseLabel>
); );
}; };
ColoredLabel.propTypes = { ColoredLabel.propTypes = {
label: PropTypes.string.isRequired, label: PropTypes.string.isRequired,
color: PropTypes.string.isRequired, color: PropTypes.string.isRequired,
}; };
/** /**
@@ -126,69 +123,63 @@ ColoredLabel.propTypes = {
*/ */
const StatusLabel = ({ status, text, customStyles }) => { const StatusLabel = ({ status, text, customStyles }) => {
const theme = useTheme(); const theme = useTheme();
const colors = { const colors = {
up: { up: {
dotColor: theme.palette.success.main, dotColor: theme.palette.success.main,
bgColor: theme.palette.success.bg, bgColor: theme.palette.success.bg,
borderColor: theme.palette.success.light, borderColor: theme.palette.success.light,
}, },
down: { down: {
dotColor: theme.palette.error.text, dotColor: theme.palette.error.text,
bgColor: theme.palette.error.bg, bgColor: theme.palette.error.bg,
borderColor: theme.palette.error.light, borderColor: theme.palette.error.light,
}, },
paused: { paused: {
dotColor: theme.palette.warning.main, dotColor: theme.palette.warning.main,
bgColor: theme.palette.warning.bg, bgColor: theme.palette.warning.bg,
borderColor: theme.palette.warning.light, borderColor: theme.palette.warning.light,
}, },
pending: { pending: {
dotColor: theme.palette.warning.main, dotColor: theme.palette.warning.main,
bgColor: theme.palette.warning.bg, bgColor: theme.palette.warning.bg,
borderColor: theme.palette.warning.light, borderColor: theme.palette.warning.light,
}, },
"cannot resolve": { "cannot resolve": {
dotColor: theme.palette.unresolved.main, dotColor: theme.palette.unresolved.main,
bgColor: theme.palette.unresolved.bg, bgColor: theme.palette.unresolved.bg,
borderColor: theme.palette.unresolved.light, borderColor: theme.palette.unresolved.light,
}, },
}; };
// Look up the color for the status // Look up the color for the status
const { borderColor, bgColor, dotColor } = colors[status]; const { borderColor, bgColor, dotColor } = colors[status];
return ( return (
<BaseLabel <BaseLabel
label={text} label={text}
styles={{ styles={{
color: dotColor, color: dotColor,
backgroundColor: bgColor, backgroundColor: bgColor,
borderColor: borderColor, borderColor: borderColor,
...customStyles, ...customStyles,
}} }}
> >
<Box <Box
width={7} width={7}
height={7} height={7}
bgcolor={dotColor} bgcolor={dotColor}
borderRadius="50%" borderRadius="50%"
marginRight="5px" marginRight="5px"
/> />
</BaseLabel> </BaseLabel>
); );
}; };
StatusLabel.propTypes = { StatusLabel.propTypes = {
status: PropTypes.oneOf([ status: PropTypes.oneOf(["up", "down", "paused", "pending", "cannot resolve"]),
"up", text: PropTypes.string,
"down", customStyles: PropTypes.object,
"paused",
"pending",
"cannot resolve",
]),
text: PropTypes.string,
customStyles: PropTypes.object,
}; };
export { ColoredLabel, StatusLabel }; export { ColoredLabel, StatusLabel };
+42 -42
View File
@@ -11,52 +11,52 @@ import PropTypes from "prop-types";
*/ */
const Link = ({ level, label, url }) => { const Link = ({ level, label, url }) => {
const theme = useTheme(); const theme = useTheme();
const levelConfig = { const levelConfig = {
primary: {}, primary: {},
secondary: { secondary: {
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
sx: { sx: {
":hover": { ":hover": {
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
}, },
}, },
}, },
tertiary: { tertiary: {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
sx: { sx: {
textDecoration: "underline", textDecoration: "underline",
textDecorationStyle: "dashed", textDecorationStyle: "dashed",
textDecorationColor: theme.palette.primary.main, textDecorationColor: theme.palette.primary.main,
textUnderlineOffset: "1px", textUnderlineOffset: "1px",
":hover": { ":hover": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
textDecorationColor: theme.palette.primary.main, textDecorationColor: theme.palette.primary.main,
backgroundColor: theme.palette.background.fill, backgroundColor: theme.palette.background.fill,
}, },
}, },
}, },
error: {}, error: {},
}; };
const { sx, color } = levelConfig[level]; const { sx, color } = levelConfig[level];
return ( return (
<MuiLink <MuiLink
href={url} href={url}
sx={{ width: "fit-content", ...sx }} sx={{ width: "fit-content", ...sx }}
color={color} color={color}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >
{label} {label}
</MuiLink> </MuiLink>
); );
}; };
Link.propTypes = { Link.propTypes = {
url: PropTypes.string.isRequired, url: PropTypes.string.isRequired,
level: PropTypes.oneOf(["primary", "secondary", "tertiary", "error"]), level: PropTypes.oneOf(["primary", "secondary", "tertiary", "error"]),
label: PropTypes.string.isRequired, label: PropTypes.string.isRequired,
}; };
export default Link; export default Link;
+3 -3
View File
@@ -1,10 +1,10 @@
.progress-bar-container h2.MuiTypography-root, .progress-bar-container h2.MuiTypography-root,
.progress-bar-container p.MuiTypography-root { .progress-bar-container p.MuiTypography-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.progress-bar-container p.MuiTypography-root:has(span) { .progress-bar-container p.MuiTypography-root:has(span) {
font-size: 12px; font-size: 12px;
} }
.progress-bar-container p.MuiTypography-root span { .progress-bar-container p.MuiTypography-root span {
padding-left: 2px; padding-left: 2px;
} }
+154 -158
View File
@@ -1,13 +1,7 @@
import React from "react"; import React from "react";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import { Box, IconButton, LinearProgress, Stack, Typography } from "@mui/material";
Box,
IconButton,
LinearProgress,
Stack,
Typography,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close"; import CloseIcon from "@mui/icons-material/Close";
import ErrorOutlineOutlinedIcon from "@mui/icons-material/ErrorOutlineOutlined"; import ErrorOutlineOutlinedIcon from "@mui/icons-material/ErrorOutlineOutlined";
import "./index.css"; import "./index.css";
@@ -23,161 +17,163 @@ import "./index.css";
* @returns {JSX.Element} The rendered component. * @returns {JSX.Element} The rendered component.
*/ */
const ProgressUpload = ({ const ProgressUpload = ({ icon, label, size, progress = 0, onClick, error }) => {
icon, const theme = useTheme();
label,
size,
progress = 0,
onClick,
error,
}) => {
const theme = useTheme();
return ( return (
<Box <Box
className="progress-bar-container" className="progress-bar-container"
mt={theme.spacing(10)} mt={theme.spacing(10)}
p={theme.spacing(8)} p={theme.spacing(8)}
sx={{ sx={{
minWidth: "200px", minWidth: "200px",
height: "fit-content", height: "fit-content",
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
border: 1, border: 1,
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
backgroundColor: theme.palette.background.fill, backgroundColor: theme.palette.background.fill,
"&:has(.input-error)": { "&:has(.input-error)": {
borderColor: theme.palette.error.main, borderColor: theme.palette.error.main,
backgroundColor: theme.palette.error.bg, backgroundColor: theme.palette.error.bg,
py: theme.spacing(4), py: theme.spacing(4),
px: theme.spacing(8), px: theme.spacing(8),
"& > .MuiStack-root > svg": { "& > .MuiStack-root > svg": {
fill: theme.palette.error.text, fill: theme.palette.error.text,
width: "20px", width: "20px",
height: "20px", height: "20px",
}, },
}, },
}} }}
> >
<Stack <Stack
direction="row" direction="row"
mb={error ? 0 : theme.spacing(5)} mb={error ? 0 : theme.spacing(5)}
gap={theme.spacing(5)} gap={theme.spacing(5)}
alignItems={error ? "center" : "flex-start"} alignItems={error ? "center" : "flex-start"}
> >
{error ? ( {error ? (
<ErrorOutlineOutlinedIcon /> <ErrorOutlineOutlinedIcon />
) : icon ? ( ) : icon ? (
<Box <Box
sx={{ sx={{
position: "relative", position: "relative",
height: 30, height: 30,
minWidth: 30, minWidth: 30,
border: 1, border: 1,
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
borderRadius: 2, borderRadius: 2,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
"& svg": { "& svg": {
position: "absolute", position: "absolute",
top: "50%", top: "50%",
left: "50%", left: "50%",
transform: "translate(-50%, -50%)", transform: "translate(-50%, -50%)",
width: 23, width: 23,
height: 23, height: 23,
"& path": { "& path": {
fill: theme.palette.other.icon, fill: theme.palette.other.icon,
}, },
}, },
}} }}
> >
{icon} {icon}
</Box> </Box>
) : ( ) : (
"" ""
)} )}
{error ? ( {error ? (
<Typography <Typography
component="p" component="p"
className="input-error" className="input-error"
color={theme.palette.error.text} color={theme.palette.error.text}
> >
{error} {error}
</Typography> </Typography>
) : ( ) : (
<Box color={theme.palette.text.tertiary}> <Box color={theme.palette.text.tertiary}>
<Typography component="h2" mb={theme.spacing(1.5)}> <Typography
{error ? error : label} component="h2"
</Typography> mb={theme.spacing(1.5)}
<Typography component="p" sx={{ opacity: 0.6 }}> >
{!error && size} {error ? error : label}
</Typography> </Typography>
</Box> <Typography
)} component="p"
<IconButton sx={{ opacity: 0.6 }}
onClick={onClick} >
sx={ {!error && size}
!error </Typography>
? { </Box>
alignSelf: "flex-start", )}
ml: "auto", <IconButton
mr: theme.spacing(-2.5), onClick={onClick}
mt: theme.spacing(-2.5), sx={
padding: theme.spacing(2.5), !error
"&:focus": { ? {
outline: "none", alignSelf: "flex-start",
}, ml: "auto",
} mr: theme.spacing(-2.5),
: { mt: theme.spacing(-2.5),
ml: "auto", padding: theme.spacing(2.5),
"&:focus": { "&:focus": {
outline: "none", outline: "none",
}, },
} }
} : {
> ml: "auto",
<CloseIcon "&:focus": {
sx={{ outline: "none",
fontSize: "20px", },
}} }
/> }
</IconButton> >
</Stack> <CloseIcon
{!error ? ( sx={{
<Stack direction="row" alignItems="center"> fontSize: "20px",
<Box sx={{ width: "100%", mr: theme.spacing(5) }}> }}
<LinearProgress />
variant="determinate" </IconButton>
value={progress} </Stack>
sx={{ {!error ? (
width: "100%", <Stack
height: "10px", direction="row"
borderRadius: theme.shape.borderRadius, alignItems="center"
maxWidth: "500px", >
backgroundColor: theme.palette.border.light, <Box sx={{ width: "100%", mr: theme.spacing(5) }}>
}} <LinearProgress
/> variant="determinate"
</Box> value={progress}
<Typography sx={{
component="p" width: "100%",
sx={{ minWidth: "max-content", opacity: 0.6 }} height: "10px",
> borderRadius: theme.shape.borderRadius,
{progress} maxWidth: "500px",
<span>%</span> backgroundColor: theme.palette.border.light,
</Typography> }}
</Stack> />
) : ( </Box>
"" <Typography
)} component="p"
</Box> sx={{ minWidth: "max-content", opacity: 0.6 }}
); >
{progress}
<span>%</span>
</Typography>
</Stack>
) : (
""
)}
</Box>
);
}; };
ProgressUpload.propTypes = { ProgressUpload.propTypes = {
icon: PropTypes.element, // JSX element for the icon (optional) icon: PropTypes.element, // JSX element for the icon (optional)
label: PropTypes.string.isRequired, // Label text for the progress item label: PropTypes.string.isRequired, // Label text for the progress item
size: PropTypes.string.isRequired, // Size information for the progress item size: PropTypes.string.isRequired, // Size information for the progress item
progress: PropTypes.number.isRequired, // Current progress value (0-100) progress: PropTypes.number.isRequired, // Current progress value (0-100)
onClick: PropTypes.func.isRequired, // Function to handle click events on the remove button onClick: PropTypes.func.isRequired, // Function to handle click events on the remove button
error: PropTypes.string, // Error message to display if there's an error (optional) error: PropTypes.string, // Error message to display if there's an error (optional)
}; };
export default ProgressUpload; export default ProgressUpload;
+42 -33
View File
@@ -5,17 +5,17 @@ import CheckCircle from "@mui/icons-material/CheckCircle";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
const CustomStepIcon = (props) => { const CustomStepIcon = (props) => {
const { completed, active } = props; const { completed, active } = props;
return completed ? ( return completed ? (
<CheckCircle color="primary" /> <CheckCircle color="primary" />
) : ( ) : (
<RadioButtonCheckedIcon color={active ? "primary" : "disabled"} /> <RadioButtonCheckedIcon color={active ? "primary" : "disabled"} />
); );
}; };
CustomStepIcon.propTypes = { CustomStepIcon.propTypes = {
completed: PropTypes.bool.isRequired, completed: PropTypes.bool.isRequired,
active: PropTypes.bool.isRequired, active: PropTypes.bool.isRequired,
}; };
/** /**
@@ -25,34 +25,43 @@ CustomStepIcon.propTypes = {
*/ */
const ProgressStepper = ({ steps }) => { const ProgressStepper = ({ steps }) => {
const [activeStep, setActiveStep] = React.useState(1); const [activeStep, setActiveStep] = React.useState(1);
return ( return (
<Stepper activeStep={activeStep} alternativeLabel> <Stepper
{steps.map((step, index) => { activeStep={activeStep}
const color = activeStep === index ? "primary" : "inherit"; alternativeLabel
return ( >
<Step key={step.label} onClick={() => setActiveStep(index)}> {steps.map((step, index) => {
<StepLabel StepIconComponent={CustomStepIcon}> const color = activeStep === index ? "primary" : "inherit";
<Typography return (
variant="body1" <Step
color={color} key={step.label}
sx={{ fontWeight: "bold" }} onClick={() => setActiveStep(index)}
> >
{step.label} <StepLabel StepIconComponent={CustomStepIcon}>
</Typography> <Typography
</StepLabel> variant="body1"
<Typography variant="body1" color={color}> color={color}
{step.content} sx={{ fontWeight: "bold" }}
</Typography> >
</Step> {step.label}
); </Typography>
})} </StepLabel>
</Stepper> <Typography
); variant="body1"
color={color}
>
{step.content}
</Typography>
</Step>
);
})}
</Stepper>
);
}; };
ProgressStepper.propTypes = { ProgressStepper.propTypes = {
steps: PropTypes.array.isRequired, steps: PropTypes.array.isRequired,
}; };
export default ProgressStepper; export default ProgressStepper;
+10 -7
View File
@@ -14,17 +14,20 @@ import PropTypes from "prop-types";
*/ */
const ProtectedRoute = ({ Component, ...rest }) => { const ProtectedRoute = ({ Component, ...rest }) => {
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
return authState.authToken ? ( return authState.authToken ? (
<Component {...rest} /> <Component {...rest} />
) : ( ) : (
<Navigate to="/login" replace /> <Navigate
); to="/login"
replace
/>
);
}; };
ProtectedRoute.propTypes = { ProtectedRoute.propTypes = {
Component: PropTypes.elementType.isRequired, Component: PropTypes.elementType.isRequired,
}; };
export default ProtectedRoute; export default ProtectedRoute;
+44 -44
View File
@@ -1,94 +1,94 @@
aside .MuiList-root svg { aside .MuiList-root svg {
width: 20px; width: 20px;
height: 20px; height: 20px;
opacity: 0.9; opacity: 0.9;
} }
aside span.MuiTypography-root { aside span.MuiTypography-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
line-height: 1; line-height: 1;
} }
aside .MuiStack-root + span.MuiTypography-root { aside .MuiStack-root + span.MuiTypography-root {
font-size: var(--env-var-font-size-medium-plus); font-size: var(--env-var-font-size-medium-plus);
} }
aside .MuiListSubheader-root { aside .MuiListSubheader-root {
font-size: var(--env-var-font-size-small); font-size: var(--env-var-font-size-small);
font-weight: 500; font-weight: 500;
line-height: 1.5; line-height: 1.5;
text-transform: uppercase; text-transform: uppercase;
margin-bottom: 2px; margin-bottom: 2px;
opacity: 0.6; opacity: 0.6;
} }
aside p.MuiTypography-root { aside p.MuiTypography-root {
font-size: var(--env-var-font-size-small); font-size: var(--env-var-font-size-small);
opacity: 0.8; opacity: 0.8;
} }
aside .MuiListItemButton-root:not(.selected-path) > * { aside .MuiListItemButton-root:not(.selected-path) > * {
opacity: 0.9; opacity: 0.9;
} }
aside .selected-path > * { aside .selected-path > * {
opacity: 1; opacity: 1;
} }
aside .selected-path span.MuiTypography-root { aside .selected-path span.MuiTypography-root {
font-weight: 600; font-weight: 600;
} }
aside .MuiCollapse-wrapperInner .MuiList-root > .MuiListItemButton-root { aside .MuiCollapse-wrapperInner .MuiList-root > .MuiListItemButton-root {
position: relative; position: relative;
} }
aside .MuiCollapse-wrapperInner .MuiList-root svg, aside .MuiCollapse-wrapperInner .MuiList-root svg,
aside .MuiList-root .MuiListItemText-root + svg { aside .MuiList-root .MuiListItemText-root + svg {
width: 18px; width: 18px;
height: 18px; height: 18px;
} }
.sidebar-popup li.MuiButtonBase-root:has(.MuiBox-root) { .sidebar-popup li.MuiButtonBase-root:has(.MuiBox-root) {
padding-bottom: 0; padding-bottom: 0;
} }
.sidebar-popup svg { .sidebar-popup svg {
width: 16px; width: 16px;
height: 16px; height: 16px;
opacity: 0.9; opacity: 0.9;
} }
/* TRANSITIONS */ /* TRANSITIONS */
aside { aside {
flex: 1; flex: 1;
transition: max-width 650ms cubic-bezier(0.36, -0.01, 0, 0.77); transition: max-width 650ms cubic-bezier(0.36, -0.01, 0, 0.77);
} }
.home-layout aside.collapsed { .home-layout aside.collapsed {
max-width: 64px; max-width: 64px;
} }
aside.expanded .MuiTypography-root, aside.expanded .MuiTypography-root,
aside.expanded p.MuiTypography-root, aside.expanded p.MuiTypography-root,
aside.expanded .MuiListItemText-root + svg, aside.expanded .MuiListItemText-root + svg,
aside.expanded .MuiAvatar-root + .MuiBox-root + .MuiIconButton-root { aside.expanded .MuiAvatar-root + .MuiBox-root + .MuiIconButton-root {
visibility: visible; visibility: visible;
animation: fadeIn 1s ease; animation: fadeIn 1s ease;
} }
aside.collapsed .MuiTypography-root, aside.collapsed .MuiTypography-root,
aside.collapsed p.MuiTypography-root, aside.collapsed p.MuiTypography-root,
aside.collapsed .MuiListItemText-root + svg, aside.collapsed .MuiListItemText-root + svg,
aside.collapsed .MuiAvatar-root + .MuiBox-root + .MuiIconButton-root { aside.collapsed .MuiAvatar-root + .MuiBox-root + .MuiIconButton-root {
opacity: 0; opacity: 0;
visibility: hidden; visibility: hidden;
} }
aside .MuiListSubheader-root { aside .MuiListSubheader-root {
transition: padding 200ms ease; transition: padding 200ms ease;
} }
@keyframes fadeIn { @keyframes fadeIn {
0% { 0% {
opacity: 0; opacity: 0;
visibility: hidden; visibility: hidden;
} }
30% { 30% {
opacity: 0; opacity: 0;
visibility: hidden; visibility: hidden;
} }
100% { 100% {
opacity: 0.9; opacity: 0.9;
visibility: visible; visibility: visible;
} }
} }
File diff suppressed because it is too large. Load diff
@@ -17,183 +17,186 @@ import { createToast } from "../../../Utils/toastUtils";
*/ */
const PasswordPanel = () => { const PasswordPanel = () => {
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
//redux state //redux state
const { authToken, isLoading } = useSelector((state) => state.auth); const { authToken, isLoading } = useSelector((state) => state.auth);
const idToName = { const idToName = {
"edit-current-password": "password", "edit-current-password": "password",
"edit-new-password": "newPassword", "edit-new-password": "newPassword",
"edit-confirm-password": "confirm", "edit-confirm-password": "confirm",
}; };
const [localData, setLocalData] = useState({ const [localData, setLocalData] = useState({
password: "", password: "",
newPassword: "", newPassword: "",
confirm: "", confirm: "",
}); });
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
const name = idToName[id]; const name = idToName[id];
setLocalData((prev) => ({ setLocalData((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
const validation = credentials.validate( const validation = credentials.validate(
{ [name]: value }, { [name]: value },
{ abortEarly: false, context: { password: localData.newPassword } } { abortEarly: false, context: { password: localData.newPassword } }
); );
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (validation.error) { if (validation.error) {
updatedErrors[name] = validation.error.details[0].message; updatedErrors[name] = validation.error.details[0].message;
} else { } else {
delete updatedErrors[name]; delete updatedErrors[name];
} }
return updatedErrors; return updatedErrors;
}); });
}; };
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const { error } = credentials.validate(localData, { const { error } = credentials.validate(localData, {
abortEarly: false, abortEarly: false,
context: { password: localData.newPassword }, context: { password: localData.newPassword },
}); });
if (error) { if (error) {
const newErrors = {}; const newErrors = {};
error.details.forEach((err) => { error.details.forEach((err) => {
newErrors[err.path[0]] = err.message; newErrors[err.path[0]] = err.message;
}); });
setErrors(newErrors); setErrors(newErrors);
} else { } else {
const action = await dispatch(update({ authToken, localData })); const action = await dispatch(update({ authToken, localData }));
if (action.payload.success) { if (action.payload.success) {
createToast({ createToast({
body: "Your password was changed successfully.", body: "Your password was changed successfully.",
}); });
setLocalData({ setLocalData({
password: "", password: "",
newPassword: "", newPassword: "",
confirm: "", confirm: "",
}); });
} else { } else {
// TODO: Check for other errors? // TODO: Check for other errors?
createToast({ createToast({
body: "Your password input was incorrect.", body: "Your password input was incorrect.",
}); });
setErrors({ password: "*" + action.payload.msg + "." }); setErrors({ password: "*" + action.payload.msg + "." });
} }
} }
}; };
return ( return (
<TabPanel <TabPanel
value="password" value="password"
sx={{ sx={{
"& h1, & input": { "& h1, & input": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
}} }}
> >
<Stack <Stack
component="form" component="form"
onSubmit={handleSubmit} onSubmit={handleSubmit}
noValidate noValidate
spellCheck="false" spellCheck="false"
gap={theme.spacing(20)} gap={theme.spacing(20)}
> >
<Stack direction="row"> <Stack direction="row">
<Box flex={0.9}> <Box flex={0.9}>
<Typography component="h1">Current password</Typography> <Typography component="h1">Current password</Typography>
</Box> </Box>
<Field <Field
type="text" type="text"
id="hidden-username" id="hidden-username"
name="username" name="username"
autoComplete="username" autoComplete="username"
hidden={true} hidden={true}
value="" value=""
/> />
<Field <Field
type="password" type="password"
id="edit-current-password" id="edit-current-password"
placeholder="Enter your current password" placeholder="Enter your current password"
autoComplete="current-password" autoComplete="current-password"
value={localData.password} value={localData.password}
onChange={handleChange} onChange={handleChange}
error={errors[idToName["edit-current-password"]]} error={errors[idToName["edit-current-password"]]}
/> />
</Stack> </Stack>
<Stack direction="row"> <Stack direction="row">
<Box flex={0.9}> <Box flex={0.9}>
<Typography component="h1">New password</Typography> <Typography component="h1">New password</Typography>
</Box> </Box>
<Field <Field
type="password" type="password"
id="edit-new-password" id="edit-new-password"
placeholder="Enter your new password" placeholder="Enter your new password"
autoComplete="new-password" autoComplete="new-password"
value={localData.newPassword} value={localData.newPassword}
onChange={handleChange} onChange={handleChange}
error={errors[idToName["edit-new-password"]]} error={errors[idToName["edit-new-password"]]}
/> />
</Stack> </Stack>
<Stack direction="row"> <Stack direction="row">
<Box flex={0.9}> <Box flex={0.9}>
<Typography component="h1">Confirm new password</Typography> <Typography component="h1">Confirm new password</Typography>
</Box> </Box>
<Field <Field
type="password" type="password"
id="edit-confirm-password" id="edit-confirm-password"
placeholder="Reenter your new password" placeholder="Reenter your new password"
autoComplete="new-password" autoComplete="new-password"
value={localData.confirm} value={localData.confirm}
onChange={handleChange} onChange={handleChange}
error={errors[idToName["edit-confirm-password"]]} error={errors[idToName["edit-confirm-password"]]}
/> />
</Stack> </Stack>
<Stack direction="row"> <Stack direction="row">
<Box flex={0.9}></Box> <Box flex={0.9}></Box>
<Box sx={{ flex: 1 }}> <Box sx={{ flex: 1 }}>
<Alert <Alert
variant="warning" variant="warning"
body="New password must contain at least 8 characters and must have at least one uppercase letter, one number and one symbol." body="New password must contain at least 8 characters and must have at least one uppercase letter, one number and one symbol."
/> />
</Box> </Box>
</Stack> </Stack>
<Stack direction="row" justifyContent="flex-end"> <Stack
<LoadingButton direction="row"
variant="contained" justifyContent="flex-end"
color="primary" >
onClick={handleSubmit} <LoadingButton
loading={isLoading} variant="contained"
loadingIndicator="Saving..." color="primary"
disabled={Object.keys(errors).length !== 0 && true} onClick={handleSubmit}
sx={{ loading={isLoading}
px: theme.spacing(12), loadingIndicator="Saving..."
mt: theme.spacing(20), disabled={Object.keys(errors).length !== 0 && true}
}} sx={{
> px: theme.spacing(12),
Save mt: theme.spacing(20),
</LoadingButton> }}
</Stack> >
</Stack> Save
</TabPanel> </LoadingButton>
); </Stack>
</Stack>
</TabPanel>
);
}; };
PasswordPanel.propTypes = { PasswordPanel.propTypes = {
// No props are being passed to this component, hence no specific PropTypes are defined. // No props are being passed to this component, hence no specific PropTypes are defined.
}; };
export default PasswordPanel; export default PasswordPanel;
@@ -7,11 +7,7 @@ import Field from "../../Inputs/Field";
import ImageField from "../../Inputs/Image"; import ImageField from "../../Inputs/Image";
import { credentials, imageValidation } from "../../../Validation/validation"; import { credentials, imageValidation } from "../../../Validation/validation";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { import { clearAuthState, deleteUser, update } from "../../../Features/Auth/authSlice";
clearAuthState,
deleteUser,
update,
} from "../../../Features/Auth/authSlice";
import ImageIcon from "@mui/icons-material/Image"; import ImageIcon from "@mui/icons-material/Image";
import ProgressUpload from "../../ProgressBars"; import ProgressUpload from "../../ProgressBars";
import { formatBytes } from "../../../Utils/fileUtils"; import { formatBytes } from "../../../Utils/fileUtils";
@@ -29,471 +25,508 @@ import LoadingButton from "@mui/lab/LoadingButton";
*/ */
const ProfilePanel = () => { const ProfilePanel = () => {
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
//redux state //redux state
const { user, authToken, isLoading } = useSelector((state) => state.auth); const { user, authToken, isLoading } = useSelector((state) => state.auth);
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",
}; };
// Local state for form data, errors, and file handling // Local state for form data, errors, and file handling
const [localData, setLocalData] = useState({ const [localData, setLocalData] = useState({
firstName: user.firstName, firstName: user.firstName,
lastName: user.lastName, lastName: user.lastName,
// email: user.email, // Disabled for now // email: user.email, // Disabled for now
}); });
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [file, setFile] = useState(); const [file, setFile] = useState();
const intervalRef = useRef(null); const intervalRef = useRef(null);
const [progress, setProgress] = useState({ value: 0, isLoading: false }); const [progress, setProgress] = useState({ value: 0, isLoading: false });
// Handles input field changes and performs validation // Handles input field changes and performs validation
const handleChange = (event) => { const handleChange = (event) => {
errors["unchanged"] && clearError("unchanged"); errors["unchanged"] && clearError("unchanged");
const { value, id } = event.target; const { value, id } = event.target;
const name = idToName[id]; const name = idToName[id];
setLocalData((prev) => ({ setLocalData((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
validateField({ [name]: value }, credentials, name); validateField({ [name]: value }, credentials, name);
}; };
// Handles image file // Handles image file
const handlePicture = (event) => { const handlePicture = (event) => {
const pic = event.target.files[0]; const pic = event.target.files[0];
let error = validateField( let error = validateField({ type: pic.type, size: pic.size }, imageValidation);
{ type: pic.type, size: pic.size }, if (error) return;
imageValidation
);
if (error) return;
setProgress((prev) => ({ ...prev, isLoading: true })); setProgress((prev) => ({ ...prev, isLoading: true }));
setFile({ setFile({
src: URL.createObjectURL(pic), src: URL.createObjectURL(pic),
name: pic.name, name: pic.name,
size: formatBytes(pic.size), size: formatBytes(pic.size),
delete: false, delete: false,
}); });
//TODO - potentitally remove, will revisit in the future //TODO - potentitally remove, will revisit in the future
intervalRef.current = setInterval(() => { intervalRef.current = setInterval(() => {
const buffer = 12; const buffer = 12;
setProgress((prev) => { setProgress((prev) => {
if (prev.value + buffer >= 100) { if (prev.value + buffer >= 100) {
clearInterval(intervalRef.current); clearInterval(intervalRef.current);
return { value: 100, isLoading: false }; return { value: 100, isLoading: false };
} }
return { ...prev, value: prev.value + buffer }; return { ...prev, value: prev.value + buffer };
}); });
}, 120); }, 120);
}; };
// Validates input against provided schema and updates error state // Validates input against provided schema and updates error state
const validateField = (toValidate, schema, name = "picture") => { const validateField = (toValidate, schema, name = "picture") => {
const { error } = schema.validate(toValidate, { abortEarly: false }); const { error } = schema.validate(toValidate, { abortEarly: false });
setErrors((prev) => { setErrors((prev) => {
const prevErrors = { ...prev }; const prevErrors = { ...prev };
if (error) prevErrors[name] = error.details[0].message; if (error) prevErrors[name] = error.details[0].message;
else delete prevErrors[name]; else delete prevErrors[name];
return prevErrors; return prevErrors;
}); });
if (error) return true; if (error) return true;
}; };
// Clears specific error from errors state // Clears specific error from errors state
const clearError = (err) => { const clearError = (err) => {
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (updatedErrors[err]) delete updatedErrors[err]; if (updatedErrors[err]) delete updatedErrors[err];
return updatedErrors; return updatedErrors;
}); });
}; };
// Resets picture-related states and clears interval // Resets picture-related states and clears interval
const removePicture = () => { const removePicture = () => {
errors["picture"] && clearError("picture"); errors["picture"] && clearError("picture");
setFile({ delete: true }); setFile({ delete: true });
clearInterval(intervalRef.current); // interrupt interval if image upload is canceled prior to completing the process clearInterval(intervalRef.current); // interrupt interval if image upload is canceled prior to completing the process
setProgress({ value: 0, isLoading: false }); setProgress({ value: 0, isLoading: false });
}; };
// Opens the picture update modal // Opens the picture update modal
const openPictureModal = () => { const openPictureModal = () => {
setIsOpen("picture"); setIsOpen("picture");
setFile({ delete: localData.deleteProfileImage }); setFile({ delete: localData.deleteProfileImage });
}; };
// Closes the picture update modal and resets related states // Closes the picture update modal and resets related states
const closePictureModal = () => { const closePictureModal = () => {
errors["picture"] && clearError("picture"); errors["picture"] && clearError("picture");
setFile(); //reset file setFile(); //reset file
clearInterval(intervalRef.current); // interrupt interval if image upload is canceled prior to completing the process clearInterval(intervalRef.current); // interrupt interval if image upload is canceled prior to completing the process
setProgress({ value: 0, isLoading: false }); setProgress({ value: 0, isLoading: false });
setIsOpen(""); setIsOpen("");
}; };
// Updates profile image displayed on UI // Updates profile image displayed on UI
const handleUpdatePicture = () => { const handleUpdatePicture = () => {
setProgress({ value: 0, isLoading: false }); setProgress({ value: 0, isLoading: false });
setLocalData((prev) => ({ setLocalData((prev) => ({
...prev, ...prev,
file: file.src, file: file.src,
deleteProfileImage: false, deleteProfileImage: false,
})); }));
setIsOpen(""); setIsOpen("");
errors["unchanged"] && clearError("unchanged"); errors["unchanged"] && clearError("unchanged");
}; };
// Handles form submission to update user profile // Handles form submission to update user profile
const handleSaveProfile = async (event) => { const handleSaveProfile = async (event) => {
event.preventDefault(); event.preventDefault();
if ( if (
localData.firstName === user.firstName && localData.firstName === user.firstName &&
localData.lastName === user.lastName && localData.lastName === user.lastName &&
localData.deleteProfileImage === undefined && localData.deleteProfileImage === undefined &&
localData.file === undefined localData.file === undefined
) { ) {
createToast({ createToast({
body: "Unable to update profile — no changes detected.", body: "Unable to update profile — no changes detected.",
}); });
setErrors({ unchanged: "unable to update profile" }); setErrors({ unchanged: "unable to update profile" });
return; return;
} }
const action = await dispatch(update({ authToken, localData })); const action = await dispatch(update({ authToken, localData }));
if (action.payload.success) { if (action.payload.success) {
createToast({ createToast({
body: "Your profile data was changed successfully.", body: "Your profile data was changed successfully.",
}); });
} else { } else {
createToast({ createToast({
body: "There was an error updating your profile data.", body: "There was an error updating your profile data.",
}); });
} }
}; };
// Removes current profile image from UI // Removes current profile image from UI
const handleDeletePicture = () => { const handleDeletePicture = () => {
setLocalData((prev) => ({ setLocalData((prev) => ({
...prev, ...prev,
deleteProfileImage: true, deleteProfileImage: true,
})); }));
errors["unchanged"] && clearError("unchanged"); errors["unchanged"] && clearError("unchanged");
}; };
// Initiates the account deletion process // Initiates the account deletion process
const handleDeleteAccount = async () => { const handleDeleteAccount = async () => {
const action = await dispatch(deleteUser(authToken)); const action = await dispatch(deleteUser(authToken));
if (action.payload.success) { if (action.payload.success) {
dispatch(clearAuthState()); dispatch(clearAuthState());
dispatch(clearUptimeMonitorState()); dispatch(clearUptimeMonitorState());
} else { } else {
if (action.payload) { if (action.payload) {
// dispatch errors // dispatch errors
createToast({ createToast({
body: action.payload.msg, body: action.payload.msg,
}); });
} else { } else {
// unknown errors // unknown errors
createToast({ createToast({
body: "Unknown error.", body: "Unknown error.",
}); });
} }
} }
}; };
// Modal state and control functions // Modal state and control functions
const [isOpen, setIsOpen] = useState(""); const [isOpen, setIsOpen] = useState("");
const isModalOpen = (name) => isOpen === name; const isModalOpen = (name) => isOpen === name;
return ( return (
<TabPanel <TabPanel
value="profile" value="profile"
sx={{ sx={{
"& h1, & p, & input": { "& h1, & p, & input": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
}} }}
> >
<Stack <Stack
component="form" component="form"
className="edit-profile-form" className="edit-profile-form"
noValidate noValidate
spellCheck="false" spellCheck="false"
gap={theme.spacing(20)} gap={theme.spacing(20)}
> >
<Stack direction="row"> <Stack direction="row">
<Box flex={0.9}> <Box flex={0.9}>
<Typography component="h1">First name</Typography> <Typography component="h1">First name</Typography>
</Box> </Box>
<Field <Field
id="edit-first-name" id="edit-first-name"
value={localData.firstName} value={localData.firstName}
placeholder="Enter your first name" placeholder="Enter your first name"
autoComplete="given-name" autoComplete="given-name"
onChange={handleChange} onChange={handleChange}
error={errors[idToName["edit-first-name"]]} error={errors[idToName["edit-first-name"]]}
/> />
</Stack> </Stack>
<Stack direction="row"> <Stack direction="row">
<Box flex={0.9}> <Box flex={0.9}>
<Typography component="h1">Last name</Typography> <Typography component="h1">Last name</Typography>
</Box> </Box>
<Field <Field
id="edit-last-name" id="edit-last-name"
placeholder="Enter your last name" placeholder="Enter your last name"
autoComplete="family-name" autoComplete="family-name"
value={localData.lastName} value={localData.lastName}
onChange={handleChange} onChange={handleChange}
error={errors[idToName["edit-last-name"]]} error={errors[idToName["edit-last-name"]]}
/> />
</Stack> </Stack>
<Stack direction="row"> <Stack direction="row">
<Stack flex={0.9}> <Stack flex={0.9}>
<Typography component="h1">Email</Typography> <Typography component="h1">Email</Typography>
<Typography component="p" sx={{ opacity: 0.6 }}> <Typography
This is your current email address — it cannot be changed. component="p"
</Typography> sx={{ opacity: 0.6 }}
</Stack> >
<Field This is your current email address — it cannot be changed.
id="edit-email" </Typography>
value={user.email} </Stack>
placeholder="Enter your email" <Field
autoComplete="email" id="edit-email"
onChange={() => logger.warn("disabled")} value={user.email}
// error={errors[idToName["edit-email"]]} placeholder="Enter your email"
disabled={true} autoComplete="email"
/> onChange={() => logger.warn("disabled")}
</Stack> // error={errors[idToName["edit-email"]]}
<Stack direction="row"> disabled={true}
<Stack flex={0.9}> />
<Typography component="h1">Your photo</Typography> </Stack>
<Typography component="p" sx={{ opacity: 0.6 }}> <Stack direction="row">
This photo will be displayed in your profile page. <Stack flex={0.9}>
</Typography> <Typography component="h1">Your photo</Typography>
</Stack> <Typography
<Stack direction="row" alignItems="center" flex={1}> component="p"
<Avatar sx={{ opacity: 0.6 }}
src={ >
localData?.deleteProfileImage This photo will be displayed in your profile page.
? "/static/images/avatar/2.jpg" </Typography>
: localData?.file </Stack>
? localData.file <Stack
: "" direction="row"
} alignItems="center"
sx={{ mr: "8px" }} flex={1}
/> >
<Button variant="text" color="info" onClick={handleDeletePicture}> <Avatar
Delete src={
</Button> localData?.deleteProfileImage
<Button variant="text" color="primary" onClick={openPictureModal}> ? "/static/images/avatar/2.jpg"
Update : localData?.file
</Button> ? localData.file
</Stack> : ""
</Stack> }
<Divider sx={{ mr: "8px" }}
aria-hidden="true" />
width="0" <Button
sx={{ variant="text"
marginY: theme.spacing(1), color="info"
}} onClick={handleDeletePicture}
/> >
<Stack direction="row" justifyContent="flex-end"> Delete
<Box width="fit-content"> </Button>
<LoadingButton <Button
variant="contained" variant="text"
color="primary" color="primary"
onClick={handleSaveProfile} onClick={openPictureModal}
loading={isLoading} >
loadingIndicator="Saving..." Update
disabled={ </Button>
Object.keys(errors).length !== 0 && !errors?.picture && true </Stack>
} </Stack>
sx={{ px: theme.spacing(12) }} <Divider
> aria-hidden="true"
Save width="0"
</LoadingButton> sx={{
</Box> marginY: theme.spacing(1),
</Stack> }}
</Stack> />
<Divider <Stack
aria-hidden="true" direction="row"
sx={{ justifyContent="flex-end"
marginY: theme.spacing(20), >
borderColor: theme.palette.border.light, <Box width="fit-content">
}} <LoadingButton
/> variant="contained"
{!user.role.includes("demo") && ( color="primary"
<Box component="form" noValidate spellCheck="false"> onClick={handleSaveProfile}
<Box mb={theme.spacing(6)}> loading={isLoading}
<Typography component="h1">Delete account</Typography> loadingIndicator="Saving..."
<Typography component="p" sx={{ opacity: 0.6 }}> disabled={Object.keys(errors).length !== 0 && !errors?.picture && true}
Note that deleting your account will remove all data from our sx={{ px: theme.spacing(12) }}
system. This is permanent and non-recoverable. >
</Typography> Save
</Box> </LoadingButton>
<Button </Box>
variant="contained" </Stack>
color="error" </Stack>
onClick={() => setIsOpen("delete")} <Divider
> aria-hidden="true"
Delete account sx={{
</Button> marginY: theme.spacing(20),
</Box> borderColor: theme.palette.border.light,
)} }}
{/* TODO - Update ModalPopup Component with @mui for reusability */} />
<Modal {!user.role.includes("demo") && (
aria-labelledby="modal-delete-account" <Box
aria-describedby="delete-account-confirmation" component="form"
open={isModalOpen("delete")} noValidate
onClose={() => setIsOpen("")} spellCheck="false"
disablePortal >
> <Box mb={theme.spacing(6)}>
<Stack <Typography component="h1">Delete account</Typography>
gap={theme.spacing(5)} <Typography
sx={{ component="p"
position: "absolute", sx={{ opacity: 0.6 }}
top: "50%", >
left: "50%", Note that deleting your account will remove all data from our system. This
transform: "translate(-50%, -50%)", is permanent and non-recoverable.
width: 500, </Typography>
bgcolor: theme.palette.background.main, </Box>
border: 1, <Button
borderColor: theme.palette.border.light, variant="contained"
borderRadius: theme.shape.borderRadius, color="error"
boxShadow: 24, onClick={() => setIsOpen("delete")}
p: theme.spacing(15), >
"&:focus": { Delete account
outline: "none", </Button>
}, </Box>
}} )}
> {/* TODO - Update ModalPopup Component with @mui for reusability */}
<Typography id="modal-delete-account" component="h1"> <Modal
Really delete this account? aria-labelledby="modal-delete-account"
</Typography> aria-describedby="delete-account-confirmation"
<Typography id="delete-account-confirmation" component="p"> open={isModalOpen("delete")}
If you delete your account, you will no longer be able to sign in, onClose={() => setIsOpen("")}
and all of your data will be deleted. Deleting your account is disablePortal
permanent and non-recoverable action. >
</Typography> <Stack
<Stack gap={theme.spacing(5)}
direction="row" sx={{
gap={theme.spacing(5)} position: "absolute",
mt={theme.spacing(5)} top: "50%",
justifyContent="flex-end" left: "50%",
> transform: "translate(-50%, -50%)",
<Button variant="text" color="info" onClick={() => setIsOpen("")}> width: 500,
Cancel bgcolor: theme.palette.background.main,
</Button> border: 1,
<LoadingButton borderColor: theme.palette.border.light,
variant="contained" borderRadius: theme.shape.borderRadius,
color="error" boxShadow: 24,
onClick={handleDeleteAccount} p: theme.spacing(15),
loading={isLoading} "&:focus": {
> outline: "none",
Delete account },
</LoadingButton> }}
</Stack> >
</Stack> <Typography
</Modal> id="modal-delete-account"
<Modal component="h1"
aria-labelledby="modal-update-picture" >
aria-describedby="update-profile-picture" Really delete this account?
open={isModalOpen("picture")} </Typography>
onClose={closePictureModal} <Typography
> id="delete-account-confirmation"
<Stack component="p"
sx={{ >
position: "absolute", If you delete your account, you will no longer be able to sign in, and all of
top: "50%", your data will be deleted. Deleting your account is permanent and
left: "50%", non-recoverable action.
transform: "translate(-50%, -50%)", </Typography>
width: 475, <Stack
bgcolor: theme.palette.background.main, direction="row"
border: 1, gap={theme.spacing(5)}
borderColor: theme.palette.border.light, mt={theme.spacing(5)}
borderRadius: theme.shape.borderRadius, justifyContent="flex-end"
boxShadow: theme.shape.boxShadow, >
p: theme.spacing(15), <Button
"&:focus": { variant="text"
outline: "none", color="info"
}, onClick={() => setIsOpen("")}
}} >
> Cancel
<Typography </Button>
id="modal-update-picture" <LoadingButton
component="h1" variant="contained"
color={theme.palette.text.secondary} color="error"
> onClick={handleDeleteAccount}
Upload Image loading={isLoading}
</Typography> >
<ImageField Delete account
id="update-profile-picture" </LoadingButton>
src={ </Stack>
file?.delete </Stack>
? "" </Modal>
: file?.src <Modal
? file.src aria-labelledby="modal-update-picture"
: localData?.file aria-describedby="update-profile-picture"
? localData.file open={isModalOpen("picture")}
: user?.avatarImage onClose={closePictureModal}
? `data:image/png;base64,${user.avatarImage}` >
: "" <Stack
} sx={{
loading={progress.isLoading && progress.value !== 100} position: "absolute",
onChange={handlePicture} top: "50%",
/> left: "50%",
{progress.isLoading || progress.value !== 0 || errors["picture"] ? ( transform: "translate(-50%, -50%)",
<ProgressUpload width: 475,
icon={<ImageIcon />} bgcolor: theme.palette.background.main,
label={file?.name} border: 1,
size={file?.size} borderColor: theme.palette.border.light,
progress={progress.value} borderRadius: theme.shape.borderRadius,
onClick={removePicture} boxShadow: theme.shape.boxShadow,
error={errors["picture"]} p: theme.spacing(15),
/> "&:focus": {
) : ( outline: "none",
"" },
)} }}
<Stack >
direction="row" <Typography
mt={theme.spacing(10)} id="modal-update-picture"
gap={theme.spacing(5)} component="h1"
justifyContent="flex-end" color={theme.palette.text.secondary}
> >
<Button variant="text" color="info" onClick={removePicture}> Upload Image
Remove </Typography>
</Button> <ImageField
<Button id="update-profile-picture"
variant="contained" src={
color="primary" file?.delete
onClick={handleUpdatePicture} ? ""
disabled={ : file?.src
(Object.keys(errors).length !== 0 && errors?.picture) || ? file.src
progress.value !== 100 : localData?.file
? true ? localData.file
: false : user?.avatarImage
} ? `data:image/png;base64,${user.avatarImage}`
> : ""
Update }
</Button> loading={progress.isLoading && progress.value !== 100}
</Stack> onChange={handlePicture}
</Stack> />
</Modal> {progress.isLoading || progress.value !== 0 || errors["picture"] ? (
</TabPanel> <ProgressUpload
); icon={<ImageIcon />}
label={file?.name}
size={file?.size}
progress={progress.value}
onClick={removePicture}
error={errors["picture"]}
/>
) : (
""
)}
<Stack
direction="row"
mt={theme.spacing(10)}
gap={theme.spacing(5)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={removePicture}
>
Remove
</Button>
<Button
variant="contained"
color="primary"
onClick={handleUpdatePicture}
disabled={
(Object.keys(errors).length !== 0 && errors?.picture) ||
progress.value !== 100
? true
: false
}
>
Update
</Button>
</Stack>
</Stack>
</Modal>
</TabPanel>
);
}; };
ProfilePanel.propTypes = { ProfilePanel.propTypes = {
// No props are being passed to this component, hence no specific PropTypes are defined. // No props are being passed to this component, hence no specific PropTypes are defined.
}; };
export default ProfilePanel; export default ProfilePanel;
@@ -1,13 +1,6 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import TabPanel from "@mui/lab/TabPanel"; import TabPanel from "@mui/lab/TabPanel";
import { import { Box, Button, ButtonGroup, Modal, Stack, Typography } from "@mui/material";
Box,
Button,
ButtonGroup,
Modal,
Stack,
Typography,
} from "@mui/material";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Field from "../../Inputs/Field"; import Field from "../../Inputs/Field";
import { credentials } from "../../../Validation/validation"; import { credentials } from "../../../Validation/validation";
@@ -27,216 +20,211 @@ import LoadingButton from "@mui/lab/LoadingButton";
*/ */
const TeamPanel = () => { const TeamPanel = () => {
const roleMap = { const roleMap = {
superadmin: "Super admin", superadmin: "Super admin",
admin: "Admin", admin: "Admin",
user: "Team member", user: "Team member",
demo: "Demo User", demo: "Demo User",
}; };
const theme = useTheme(); const theme = useTheme();
const { authToken, user } = useSelector((state) => state.auth); const { authToken, user } = useSelector((state) => state.auth);
//TODO //TODO
const [orgStates, setOrgStates] = useState({ const [orgStates, setOrgStates] = useState({
name: "Bluewave Labs", name: "Bluewave Labs",
isEdit: false, isEdit: false,
}); });
const [toInvite, setToInvite] = useState({ const [toInvite, setToInvite] = useState({
email: "", email: "",
role: ["0"], role: ["0"],
}); });
const [tableData, setTableData] = useState({}); const [tableData, setTableData] = useState({});
const [members, setMembers] = useState([]); const [members, setMembers] = useState([]);
const [filter, setFilter] = useState("all"); const [filter, setFilter] = useState("all");
const [isDisabled, setIsDisabled] = useState(true); const [isDisabled, setIsDisabled] = useState(true);
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [isSendingInvite, setIsSendingInvite] = useState(false); const [isSendingInvite, setIsSendingInvite] = useState(false);
useEffect(() => { useEffect(() => {
const fetchTeam = async () => { const fetchTeam = async () => {
try { try {
const response = await networkService.getAllUsers({ const response = await networkService.getAllUsers({
authToken: authToken, authToken: authToken,
}); });
setMembers(response.data.data); setMembers(response.data.data);
} catch (error) { } catch (error) {
createToast({ createToast({
body: error.message || "Error fetching team members.", body: error.message || "Error fetching team members.",
}); });
} }
}; };
fetchTeam(); fetchTeam();
}, [user]); }, [user]);
useEffect(() => { useEffect(() => {
let team = members; let team = members;
if (filter !== "all") if (filter !== "all")
team = members.filter((member) => { team = members.filter((member) => {
if (filter === "admin") { if (filter === "admin") {
return ( return member.role.includes("admin") || member.role.includes("superadmin");
member.role.includes("admin") || member.role.includes("superadmin") }
); return member.role.includes(filter);
} });
return member.role.includes(filter);
});
const data = { const data = {
cols: [ cols: [
{ id: 1, name: "NAME" }, { id: 1, name: "NAME" },
{ id: 2, name: "EMAIL" }, { id: 2, name: "EMAIL" },
{ id: 3, name: "ROLE" }, { id: 3, name: "ROLE" },
// FEATURE STILL TO BE IMPLEMENTED // FEATURE STILL TO BE IMPLEMENTED
// { id: 4, name: "ACTION" }, // { id: 4, name: "ACTION" },
], ],
rows: team?.map((member, idx) => { rows: team?.map((member, idx) => {
const roles = member.role.map((role) => roleMap[role]).join(","); const roles = member.role.map((role) => roleMap[role]).join(",");
return { return {
id: member._id, id: member._id,
data: [ data: [
{ {
id: idx, id: idx,
data: ( data: (
<Stack> <Stack>
<Typography color={theme.palette.text.secondary}> <Typography color={theme.palette.text.secondary}>
{member.firstName + " " + member.lastName} {member.firstName + " " + member.lastName}
</Typography> </Typography>
<Typography> <Typography>
Created {new Date(member.createdAt).toLocaleDateString()} Created {new Date(member.createdAt).toLocaleDateString()}
</Typography> </Typography>
</Stack> </Stack>
), ),
}, },
{ id: idx + 1, data: member.email }, { id: idx + 1, data: member.email },
{ {
// TODO - Add select dropdown // TODO - Add select dropdown
id: idx + 2, id: idx + 2,
data: roles, data: roles,
}, },
// FEATURE STILL TO BE IMPLEMENTED // FEATURE STILL TO BE IMPLEMENTED
// { // {
// // TODO - Add delete onClick // // TODO - Add delete onClick
// id: idx + 3, // id: idx + 3,
// data: ( // data: (
// <IconButton // <IconButton
// aria-label="remove member" // aria-label="remove member"
// sx={{ // sx={{
// "&:focus": { // "&:focus": {
// outline: "none", // outline: "none",
// }, // },
// }} // }}
// > // >
// <Remove /> // <Remove />
// </IconButton> // </IconButton>
// ), // ),
// }, // },
], ],
}; };
}), }),
}; };
setTableData(data); setTableData(data);
}, [members, filter]); }, [members, filter]);
useEffect(() => { useEffect(() => {
setIsDisabled(Object.keys(errors).length !== 0 || toInvite.email === ""); setIsDisabled(Object.keys(errors).length !== 0 || toInvite.email === "");
}, [errors, toInvite.email]); }, [errors, toInvite.email]);
// RENAME ORGANIZATION // RENAME ORGANIZATION
const toggleEdit = () => { const toggleEdit = () => {
setOrgStates((prev) => ({ ...prev, isEdit: !prev.isEdit })); setOrgStates((prev) => ({ ...prev, isEdit: !prev.isEdit }));
}; };
const handleRename = () => {}; const handleRename = () => {};
// INVITE MEMBER // INVITE MEMBER
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const handleChange = (event) => { const handleChange = (event) => {
const { value } = event.target; const { value } = event.target;
setToInvite((prev) => ({ setToInvite((prev) => ({
...prev, ...prev,
email: value, email: value,
})); }));
const validation = credentials.validate( const validation = credentials.validate({ email: value }, { abortEarly: false });
{ email: value },
{ abortEarly: false }
);
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (validation.error) { if (validation.error) {
updatedErrors.email = validation.error.details[0].message; updatedErrors.email = validation.error.details[0].message;
} else { } else {
delete updatedErrors.email; delete updatedErrors.email;
} }
return updatedErrors; return updatedErrors;
}); });
}; };
const handleInviteMember = async () => { const handleInviteMember = async () => {
if (!toInvite.email) { if (!toInvite.email) {
setErrors((prev) => ({ ...prev, email: "Email is required." })); setErrors((prev) => ({ ...prev, email: "Email is required." }));
return; return;
} }
setIsSendingInvite(true); setIsSendingInvite(true);
if (!toInvite.role.includes("user") || !toInvite.role.includes("admin")) if (!toInvite.role.includes("user") || !toInvite.role.includes("admin"))
setToInvite((prev) => ({ ...prev, role: ["user"] })); setToInvite((prev) => ({ ...prev, role: ["user"] }));
const { error } = credentials.validate( const { error } = credentials.validate(
{ email: toInvite.email }, { email: toInvite.email },
{ {
abortEarly: false, abortEarly: false,
} }
); );
if (error) { if (error) {
setErrors((prev) => ({ ...prev, email: error.details[0].message })); setErrors((prev) => ({ ...prev, email: error.details[0].message }));
return; return;
} }
try { try {
await networkService.requestInvitationToken({ await networkService.requestInvitationToken({
authToken: authToken, authToken: authToken,
email: toInvite.email, email: toInvite.email,
role: toInvite.role, role: toInvite.role,
}); });
closeInviteModal(); closeInviteModal();
createToast({ createToast({
body: "Member invited. They will receive an email with details on how to create their account.", body: "Member invited. They will receive an email with details on how to create their account.",
}); });
} catch (error) { } catch (error) {
createToast({ createToast({
body: error.message || "Unknown error.", body: error.message || "Unknown error.",
}); });
} finally { } finally {
setIsSendingInvite(false); setIsSendingInvite(false);
} }
}; };
const closeInviteModal = () => { const closeInviteModal = () => {
setIsOpen(false); setIsOpen(false);
setToInvite({ email: "", role: ["0"] }); setToInvite({ email: "", role: ["0"] });
setErrors({}); setErrors({});
}; };
return ( return (
<TabPanel <TabPanel
className="team-panel table-container" className="team-panel table-container"
value="team" value="team"
sx={{ sx={{
"& h1": { "& h1": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
"& .MuiTable-root .MuiTableBody-root .MuiTableCell-root, & .MuiTable-root p + p": "& .MuiTable-root .MuiTableBody-root .MuiTableCell-root, & .MuiTable-root p + p":
{ {
color: theme.palette.text.accent, color: theme.palette.text.accent,
}, },
}} }}
> >
{/* FEATURE STILL TO BE IMPLEMENTED */} {/* FEATURE STILL TO BE IMPLEMENTED */}
{/* <Stack component="form"> {/* <Stack component="form">
<Box sx={{ alignSelf: "flex-start" }}> <Box sx={{ alignSelf: "flex-start" }}>
<Typography component="h1">Organization name</Typography> <Typography component="h1">Organization name</Typography>
</Box> </Box>
@@ -282,161 +270,163 @@ const TeamPanel = () => {
</Stack> </Stack>
</Stack> </Stack>
<Divider aria-hidden="true" sx={{ marginY: theme.spacing(4) }} /> */} <Divider aria-hidden="true" sx={{ marginY: theme.spacing(4) }} /> */}
<Stack <Stack
component="form" component="form"
noValidate noValidate
spellCheck="false" spellCheck="false"
gap={theme.spacing(12)} gap={theme.spacing(12)}
> >
<Typography component="h1">Team members</Typography> <Typography component="h1">Team members</Typography>
<Stack direction="row" justifyContent="space-between"> <Stack
<Stack direction="row"
direction="row" justifyContent="space-between"
alignItems="flex-end" >
gap={theme.spacing(6)} <Stack
sx={{ fontSize: 14 }} direction="row"
> alignItems="flex-end"
<ButtonGroup> gap={theme.spacing(6)}
<Button sx={{ fontSize: 14 }}
variant="group" >
filled={(filter === "all").toString()} <ButtonGroup>
onClick={() => setFilter("all")} <Button
> variant="group"
All filled={(filter === "all").toString()}
</Button> onClick={() => setFilter("all")}
<Button >
variant="group" All
filled={(filter === "admin").toString()} </Button>
onClick={() => setFilter("admin")} <Button
> variant="group"
Administrator filled={(filter === "admin").toString()}
</Button> onClick={() => setFilter("admin")}
<Button >
variant="group" Administrator
filled={(filter === "user").toString()} </Button>
onClick={() => setFilter("user")} <Button
> variant="group"
Member filled={(filter === "user").toString()}
</Button> onClick={() => setFilter("user")}
</ButtonGroup> >
</Stack> Member
<LoadingButton </Button>
loading={isSendingInvite} </ButtonGroup>
variant="contained" </Stack>
color="primary" <LoadingButton
onClick={() => setIsOpen(true)} loading={isSendingInvite}
> variant="contained"
Invite a team member color="primary"
</LoadingButton> onClick={() => setIsOpen(true)}
</Stack> >
<BasicTable Invite a team member
data={tableData} </LoadingButton>
paginated={false} </Stack>
reversed={true} <BasicTable
table={"team"} data={tableData}
/> paginated={false}
</Stack> reversed={true}
<Modal table={"team"}
aria-labelledby="modal-invite-member" />
aria-describedby="invite-member-to-team" </Stack>
open={isOpen} <Modal
onClose={closeInviteModal} aria-labelledby="modal-invite-member"
> aria-describedby="invite-member-to-team"
<Stack open={isOpen}
gap={theme.spacing(5)} onClose={closeInviteModal}
sx={{ >
position: "absolute", <Stack
top: "50%", gap={theme.spacing(5)}
left: "50%", sx={{
transform: "translate(-50%, -50%)", position: "absolute",
width: 450, top: "50%",
bgcolor: theme.palette.background.main, left: "50%",
border: 1, transform: "translate(-50%, -50%)",
borderColor: theme.palette.border.light, width: 450,
borderRadius: theme.shape.borderRadius, bgcolor: theme.palette.background.main,
boxShadow: theme.shape.boxShadow, border: 1,
p: theme.spacing(15), borderColor: theme.palette.border.light,
"&:focus": { borderRadius: theme.shape.borderRadius,
outline: "none", boxShadow: theme.shape.boxShadow,
}, p: theme.spacing(15),
}} "&:focus": {
> outline: "none",
<Box> },
<Typography }}
id="modal-invite-member" >
component="h1" <Box>
fontWeight={600} <Typography
fontColor={theme.palette.text.secondary} id="modal-invite-member"
> component="h1"
Invite new team member fontWeight={600}
</Typography> fontColor={theme.palette.text.secondary}
<Typography >
id="invite-member-to-team" Invite new team member
component="p" </Typography>
fontSize={13} <Typography
color={theme.palette.text.accent} id="invite-member-to-team"
sx={{ mt: theme.spacing(1), mb: theme.spacing(4) }} component="p"
> fontSize={13}
When you add a new team member, they will get access to all color={theme.palette.text.accent}
monitors. sx={{ mt: theme.spacing(1), mb: theme.spacing(4) }}
</Typography> >
</Box> When you add a new team member, they will get access to all monitors.
<Field </Typography>
type="email" </Box>
id="input-team-member" <Field
placeholder="Email" type="email"
value={toInvite.email} id="input-team-member"
onChange={handleChange} placeholder="Email"
error={errors.email} value={toInvite.email}
/> onChange={handleChange}
<Select error={errors.email}
id="team-member-role" />
placeholder="Select role" <Select
isHidden={true} id="team-member-role"
value={toInvite.role[0]} placeholder="Select role"
onChange={(event) => isHidden={true}
setToInvite((prev) => ({ value={toInvite.role[0]}
...prev, onChange={(event) =>
role: [event.target.value], setToInvite((prev) => ({
})) ...prev,
} role: [event.target.value],
items={[ }))
{ _id: "admin", name: "Admin" }, }
{ _id: "user", name: "User" }, items={[
]} { _id: "admin", name: "Admin" },
/> { _id: "user", name: "User" },
<Stack ]}
direction="row" />
gap={theme.spacing(4)} <Stack
mt={theme.spacing(8)} direction="row"
justifyContent="flex-end" gap={theme.spacing(4)}
> mt={theme.spacing(8)}
<LoadingButton justifyContent="flex-end"
loading={isSendingInvite} >
variant="text" <LoadingButton
color="info" loading={isSendingInvite}
onClick={closeInviteModal} variant="text"
> color="info"
Cancel onClick={closeInviteModal}
</LoadingButton> >
<LoadingButton Cancel
variant="contained" </LoadingButton>
color="primary" <LoadingButton
onClick={handleInviteMember} variant="contained"
loading={isSendingInvite} color="primary"
disabled={isDisabled} onClick={handleInviteMember}
> loading={isSendingInvite}
Send invite disabled={isDisabled}
</LoadingButton> >
</Stack> Send invite
</Stack> </LoadingButton>
</Modal> </Stack>
</TabPanel> </Stack>
); </Modal>
</TabPanel>
);
}; };
TeamPanel.propTypes = { TeamPanel.propTypes = {
// No props are being passed to this component, hence no specific PropTypes are defined. // No props are being passed to this component, hence no specific PropTypes are defined.
}; };
export default TeamPanel; export default TeamPanel;
+209 -225
View File
@@ -4,270 +4,254 @@ import { jwtDecode } from "jwt-decode";
import axios from "axios"; import axios from "axios";
const initialState = { const initialState = {
isLoading: false, isLoading: false,
authToken: "", authToken: "",
user: "", user: "",
success: null, success: null,
msg: null, msg: null,
}; };
export const register = createAsyncThunk( export const register = createAsyncThunk("auth/register", async (form, thunkApi) => {
"auth/register", try {
async (form, thunkApi) => { const res = await networkService.registerUser(form);
try { return res.data;
const res = await networkService.registerUser(form); } catch (error) {
return res.data; if (error.response.data) {
} catch (error) { return thunkApi.rejectWithValue(error.response.data);
if (error.response.data) { }
return thunkApi.rejectWithValue(error.response.data); const payload = {
} status: false,
const payload = { msg: error.message ? error.message : "Unknown error",
status: false, };
msg: error.message ? error.message : "Unknown error", return thunkApi.rejectWithValue(payload);
}; }
return thunkApi.rejectWithValue(payload);
}
}
);
export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
try {
const res = await networkService.loginUser(form);
return res.data;
} catch (error) {
if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data);
}
const payload = {
status: false,
msg: error.message ? error.message : "Unknown error",
};
return thunkApi.rejectWithValue(payload);
}
}); });
export const update = createAsyncThunk( export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
"auth/update", try {
async (data, thunkApi) => { const res = await networkService.loginUser(form);
const { authToken: token, localData: form } = data; return res.data;
const user = jwtDecode(token); } catch (error) {
try { if (error.response && error.response.data) {
const fd = new FormData(); return thunkApi.rejectWithValue(error.response.data);
form.firstName && fd.append("firstName", form.firstName); }
form.lastName && fd.append("lastName", form.lastName); const payload = {
form.password && fd.append("password", form.password); status: false,
form.newPassword && fd.append("newPassword", form.newPassword); msg: error.message ? error.message : "Unknown error",
if (form.file && form.file !== "") { };
const imageResult = await axios.get(form.file, { return thunkApi.rejectWithValue(payload);
responseType: "blob", }
}); });
fd.append("profileImage", imageResult.data);
}
form.deleteProfileImage &&
fd.append("deleteProfileImage", form.deleteProfileImage);
const res = await networkService.updateUser({ export const update = createAsyncThunk("auth/update", async (data, thunkApi) => {
authToken: token, const { authToken: token, localData: form } = data;
userId: user._id, const user = jwtDecode(token);
form: fd, try {
}); const fd = new FormData();
return res.data; form.firstName && fd.append("firstName", form.firstName);
} catch (error) { form.lastName && fd.append("lastName", form.lastName);
if (error.response && error.response.data) { form.password && fd.append("password", form.password);
return thunkApi.rejectWithValue(error.response.data); form.newPassword && fd.append("newPassword", form.newPassword);
} if (form.file && form.file !== "") {
const payload = { const imageResult = await axios.get(form.file, {
status: false, responseType: "blob",
msg: error.message ? error.message : "Unknown error", });
}; fd.append("profileImage", imageResult.data);
return thunkApi.rejectWithValue(payload); }
} form.deleteProfileImage && fd.append("deleteProfileImage", form.deleteProfileImage);
}
);
export const deleteUser = createAsyncThunk( const res = await networkService.updateUser({
"auth/delete", authToken: token,
async (data, thunkApi) => { userId: user._id,
const user = jwtDecode(data); form: fd,
});
return res.data;
} catch (error) {
if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data);
}
const payload = {
status: false,
msg: error.message ? error.message : "Unknown error",
};
return thunkApi.rejectWithValue(payload);
}
});
try { export const deleteUser = createAsyncThunk("auth/delete", async (data, thunkApi) => {
const res = await networkService.deleteUser({ const user = jwtDecode(data);
authToken: data,
userId: user._id, try {
}); const res = await networkService.deleteUser({
return res.data; authToken: data,
} catch (error) { userId: user._id,
if (error.response && error.response.data) { });
return thunkApi.rejectWithValue(error.response.data); return res.data;
} } catch (error) {
const payload = { if (error.response && error.response.data) {
status: false, return thunkApi.rejectWithValue(error.response.data);
msg: error.message ? error.message : "Unknown error", }
}; const payload = {
return thunkApi.rejectWithValue(payload); status: false,
} msg: error.message ? error.message : "Unknown error",
} };
); return thunkApi.rejectWithValue(payload);
}
});
export const forgotPassword = createAsyncThunk( export const forgotPassword = createAsyncThunk(
"auth/forgotPassword", "auth/forgotPassword",
async (form, thunkApi) => { async (form, thunkApi) => {
try { try {
const res = await networkService.forgotPassword(form); const res = await networkService.forgotPassword(form);
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response.data) { if (error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const setNewPassword = createAsyncThunk( export const setNewPassword = createAsyncThunk(
"auth/setNewPassword", "auth/setNewPassword",
async (data, thunkApi) => { async (data, thunkApi) => {
const { token, form } = data; const { token, form } = data;
try { try {
await networkService.validateRecoveryToken({ recoveryToken: token }); await networkService.validateRecoveryToken({ recoveryToken: token });
const res = await networkService.setNewPassword({ const res = await networkService.setNewPassword({
recoveryToken: token, recoveryToken: token,
form: form, form: form,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response.data) { if (error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
const handleAuthFulfilled = (state, action) => { const handleAuthFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
state.authToken = action.payload.data.token; state.authToken = action.payload.data.token;
state.user = action.payload.data.user; state.user = action.payload.data.user;
}; };
const handleAuthRejected = (state, action) => { const handleAuthRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to login or register";
? action.payload.msg
: "Failed to login or register";
}; };
const handleUpdateFulfilled = (state, action) => { const handleUpdateFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
state.user = action.payload.data; state.user = action.payload.data;
}; };
const handleUpdateRejected = (state, action) => { const handleUpdateRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to update profile data.";
? action.payload.msg
: "Failed to update profile data.";
}; };
const handleDeleteFulfilled = (state, action) => { const handleDeleteFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}; };
const handleDeleteRejected = (state, action) => { const handleDeleteRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload ? action.payload.msg : "Failed to delete account."; state.msg = action.payload ? action.payload.msg : "Failed to delete account.";
}; };
const handleForgotFulfilled = (state, action) => { const handleForgotFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}; };
const handleForgotRejected = (state, action) => { const handleForgotRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to send reset instructions.";
? action.payload.msg
: "Failed to send reset instructions.";
}; };
const handleNewPasswordRejected = (state, action) => { const handleNewPasswordRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload ? action.payload.msg : "Failed to reset password."; state.msg = action.payload ? action.payload.msg : "Failed to reset password.";
}; };
const authSlice = createSlice({ const authSlice = createSlice({
name: "auth", name: "auth",
initialState, initialState,
reducers: { reducers: {
clearAuthState: (state) => { clearAuthState: (state) => {
state.authToken = ""; state.authToken = "";
state.user = ""; state.user = "";
state.isLoading = false; state.isLoading = false;
state.success = true; state.success = true;
state.msg = "Logged out successfully"; state.msg = "Logged out successfully";
}, },
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
// Register thunk // Register thunk
builder builder
.addCase(register.pending, (state) => { .addCase(register.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(register.fulfilled, handleAuthFulfilled) .addCase(register.fulfilled, handleAuthFulfilled)
.addCase(register.rejected, handleAuthRejected); .addCase(register.rejected, handleAuthRejected);
// Login thunk // Login thunk
builder builder
.addCase(login.pending, (state) => { .addCase(login.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(login.fulfilled, handleAuthFulfilled) .addCase(login.fulfilled, handleAuthFulfilled)
.addCase(login.rejected, handleAuthRejected); .addCase(login.rejected, handleAuthRejected);
// Update thunk // Update thunk
builder builder
.addCase(update.pending, (state) => { .addCase(update.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(update.fulfilled, handleUpdateFulfilled) .addCase(update.fulfilled, handleUpdateFulfilled)
.addCase(update.rejected, handleUpdateRejected); .addCase(update.rejected, handleUpdateRejected);
// Delete thunk // Delete thunk
builder builder
.addCase(deleteUser.pending, (state) => { .addCase(deleteUser.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(deleteUser.fulfilled, handleDeleteFulfilled) .addCase(deleteUser.fulfilled, handleDeleteFulfilled)
.addCase(deleteUser.rejected, handleDeleteRejected); .addCase(deleteUser.rejected, handleDeleteRejected);
// Forgot password thunk // Forgot password thunk
builder builder
.addCase(forgotPassword.pending, (state) => { .addCase(forgotPassword.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(forgotPassword.fulfilled, handleForgotFulfilled) .addCase(forgotPassword.fulfilled, handleForgotFulfilled)
.addCase(forgotPassword.rejected, handleForgotRejected); .addCase(forgotPassword.rejected, handleForgotRejected);
// Set new password thunk // Set new password thunk
builder builder
.addCase(setNewPassword.pending, (state) => { .addCase(setNewPassword.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(setNewPassword.fulfilled, handleAuthFulfilled) .addCase(setNewPassword.fulfilled, handleAuthFulfilled)
.addCase(setNewPassword.rejected, handleNewPasswordRejected); .addCase(setNewPassword.rejected, handleNewPasswordRejected);
}, },
}); });
export default authSlice.reducer; export default authSlice.reducer;
@@ -2,283 +2,283 @@ import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { jwtDecode } from "jwt-decode"; import { jwtDecode } from "jwt-decode";
import { networkService } from "../../main"; import { networkService } from "../../main";
const initialState = { const initialState = {
isLoading: false, isLoading: false,
monitorsSummary: [], monitorsSummary: [],
success: null, success: null,
msg: null, msg: null,
}; };
export const createPageSpeed = createAsyncThunk( export const createPageSpeed = createAsyncThunk(
"pageSpeedMonitors/createPageSpeed", "pageSpeedMonitors/createPageSpeed",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitor } = data; const { authToken, monitor } = data;
const res = await networkService.createMonitor({ const res = await networkService.createMonitor({
authToken: authToken, authToken: authToken,
monitor: monitor, monitor: monitor,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const getPagespeedMonitorById = createAsyncThunk( export const getPagespeedMonitorById = createAsyncThunk(
"monitors/getMonitorById", "monitors/getMonitorById",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitorId } = data; const { authToken, monitorId } = data;
const res = await networkService.getMonitorById({ const res = await networkService.getMonitorById({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const getPageSpeedByTeamId = createAsyncThunk( export const getPageSpeedByTeamId = createAsyncThunk(
"pageSpeedMonitors/getPageSpeedByTeamId", "pageSpeedMonitors/getPageSpeedByTeamId",
async (token, thunkApi) => { async (token, thunkApi) => {
const user = jwtDecode(token); const user = jwtDecode(token);
try { try {
const res = await networkService.getMonitorsAndSummaryByTeamId({ const res = await networkService.getMonitorsAndSummaryByTeamId({
authToken: token, authToken: token,
teamId: user.teamId, teamId: user.teamId,
types: ["pagespeed"], types: ["pagespeed"],
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const updatePageSpeed = createAsyncThunk( export const updatePageSpeed = createAsyncThunk(
"pageSpeedMonitors/updatePageSpeed", "pageSpeedMonitors/updatePageSpeed",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitor } = data; const { authToken, monitor } = data;
const updatedFields = { const updatedFields = {
name: monitor.name, name: monitor.name,
description: monitor.description, description: monitor.description,
interval: monitor.interval, interval: monitor.interval,
// notifications: monitor.notifications, // notifications: monitor.notifications,
}; };
const res = await networkService.updateMonitor({ const res = await networkService.updateMonitor({
authToken: authToken, authToken: authToken,
monitorId: monitor._id, monitorId: monitor._id,
updatedFields: updatedFields, updatedFields: updatedFields,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const deletePageSpeed = createAsyncThunk( export const deletePageSpeed = createAsyncThunk(
"pageSpeedMonitors/deletePageSpeed", "pageSpeedMonitors/deletePageSpeed",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitor } = data; const { authToken, monitor } = data;
const res = await networkService.deleteMonitorById({ const res = await networkService.deleteMonitorById({
authToken: authToken, authToken: authToken,
monitorId: monitor._id, monitorId: monitor._id,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const pausePageSpeed = createAsyncThunk( export const pausePageSpeed = createAsyncThunk(
"pageSpeedMonitors/pausePageSpeed", "pageSpeedMonitors/pausePageSpeed",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitorId } = data; const { authToken, monitorId } = data;
const res = await networkService.pauseMonitorById({ const res = await networkService.pauseMonitorById({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
const pageSpeedMonitorSlice = createSlice({ const pageSpeedMonitorSlice = createSlice({
name: "pageSpeedMonitor", name: "pageSpeedMonitor",
initialState, initialState,
reducers: { reducers: {
clearMonitorState: (state) => { clearMonitorState: (state) => {
state.isLoading = false; state.isLoading = false;
state.monitorsSummary = []; state.monitorsSummary = [];
state.success = null; state.success = null;
state.msg = null; state.msg = null;
}, },
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
builder builder
// ***************************************************** // *****************************************************
// Monitors by teamId // Monitors by teamId
// ***************************************************** // *****************************************************
.addCase(getPageSpeedByTeamId.pending, (state) => { .addCase(getPageSpeedByTeamId.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(getPageSpeedByTeamId.fulfilled, (state, action) => { .addCase(getPageSpeedByTeamId.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.msg; state.success = action.payload.msg;
state.monitorsSummary = action.payload.data; state.monitorsSummary = action.payload.data;
}) })
.addCase(getPageSpeedByTeamId.rejected, (state, action) => { .addCase(getPageSpeedByTeamId.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Getting page speed monitors failed"; : "Getting page speed monitors failed";
}) })
// ***************************************************** // *****************************************************
.addCase(getPagespeedMonitorById.pending, (state) => { .addCase(getPagespeedMonitorById.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(getPagespeedMonitorById.fulfilled, (state, action) => { .addCase(getPagespeedMonitorById.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(getPagespeedMonitorById.rejected, (state, action) => { .addCase(getPagespeedMonitorById.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to get pagespeed monitor"; : "Failed to get pagespeed monitor";
}) })
// ***************************************************** // *****************************************************
// Create Monitor // Create Monitor
// ***************************************************** // *****************************************************
.addCase(createPageSpeed.pending, (state) => { .addCase(createPageSpeed.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(createPageSpeed.fulfilled, (state, action) => { .addCase(createPageSpeed.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(createPageSpeed.rejected, (state, action) => { .addCase(createPageSpeed.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to create page speed monitor"; : "Failed to create page speed monitor";
}) })
// ***************************************************** // *****************************************************
// Update Monitor // Update Monitor
// ***************************************************** // *****************************************************
.addCase(updatePageSpeed.pending, (state) => { .addCase(updatePageSpeed.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(updatePageSpeed.fulfilled, (state, action) => { .addCase(updatePageSpeed.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(updatePageSpeed.rejected, (state, action) => { .addCase(updatePageSpeed.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to update page speed monitor"; : "Failed to update page speed monitor";
}) })
// ***************************************************** // *****************************************************
// Delete Monitor // Delete Monitor
// ***************************************************** // *****************************************************
.addCase(deletePageSpeed.pending, (state) => { .addCase(deletePageSpeed.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(deletePageSpeed.fulfilled, (state, action) => { .addCase(deletePageSpeed.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(deletePageSpeed.rejected, (state, action) => { .addCase(deletePageSpeed.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to delete page speed monitor"; : "Failed to delete page speed monitor";
}) })
// ***************************************************** // *****************************************************
// Pause Monitor // Pause Monitor
// ***************************************************** // *****************************************************
.addCase(pausePageSpeed.pending, (state) => { .addCase(pausePageSpeed.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(pausePageSpeed.fulfilled, (state, action) => { .addCase(pausePageSpeed.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(pausePageSpeed.rejected, (state, action) => { .addCase(pausePageSpeed.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to pause page speed monitor"; : "Failed to pause page speed monitor";
}); });
}, },
}); });
export const { setMonitors, clearMonitorState } = pageSpeedMonitorSlice.actions; export const { setMonitors, clearMonitorState } = pageSpeedMonitorSlice.actions;
+89 -91
View File
@@ -2,116 +2,114 @@ import { networkService } from "../../main";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
const initialState = { const initialState = {
isLoading: false, isLoading: false,
apiBaseUrl: "", apiBaseUrl: "",
logLevel: "debug", logLevel: "debug",
}; };
export const getAppSettings = createAsyncThunk( export const getAppSettings = createAsyncThunk(
"settings/getSettings", "settings/getSettings",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const res = await networkService.getAppSettings({ const res = await networkService.getAppSettings({
authToken: data.authToken, authToken: data.authToken,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response.data) { if (error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const updateAppSettings = createAsyncThunk( export const updateAppSettings = createAsyncThunk(
"settings/updateSettings", "settings/updateSettings",
async ({ settings, authToken }, thunkApi) => { async ({ settings, authToken }, thunkApi) => {
networkService.setBaseUrl(settings.apiBaseUrl); networkService.setBaseUrl(settings.apiBaseUrl);
try { try {
const parsedSettings = { const parsedSettings = {
apiBaseUrl: settings.apiBaseUrl, apiBaseUrl: settings.apiBaseUrl,
logLevel: settings.logLevel, logLevel: settings.logLevel,
clientHost: settings.clientHost, clientHost: settings.clientHost,
jwtSecret: settings.jwtSecret, jwtSecret: settings.jwtSecret,
dbType: settings.dbType, dbType: settings.dbType,
dbConnectionString: settings.dbConnectionString, dbConnectionString: settings.dbConnectionString,
redisHost: settings.redisHost, redisHost: settings.redisHost,
redisPort: settings.redisPort, redisPort: settings.redisPort,
jwtTTL: settings.jwtTTL, jwtTTL: settings.jwtTTL,
pagespeedApiKey: settings.pagespeedApiKey, pagespeedApiKey: settings.pagespeedApiKey,
systemEmailHost: settings.systemEmailHost, systemEmailHost: settings.systemEmailHost,
systemEmailPort: settings.systemEmailPort, systemEmailPort: settings.systemEmailPort,
systemEmailAddress: settings.systemEmailAddress, systemEmailAddress: settings.systemEmailAddress,
systemEmailPassword: settings.systemEmailPassword, systemEmailPassword: settings.systemEmailPassword,
}; };
const res = await networkService.updateAppSettings({ const res = await networkService.updateAppSettings({
settings: parsedSettings, settings: parsedSettings,
authToken, authToken,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
const handleGetSettingsFulfilled = (state, action) => { const handleGetSettingsFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
state.apiBaseUrl = action.payload.data.apiBaseUrl; state.apiBaseUrl = action.payload.data.apiBaseUrl;
state.logLevel = action.payload.data.logLevel; state.logLevel = action.payload.data.logLevel;
}; };
const handleGetSettingsRejected = (state, action) => { const handleGetSettingsRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload ? action.payload.msg : "Failed to get settings."; state.msg = action.payload ? action.payload.msg : "Failed to get settings.";
}; };
const handleUpdateSettingsFulfilled = (state, action) => { const handleUpdateSettingsFulfilled = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
state.apiBaseUrl = action.payload.data.apiBaseUrl; state.apiBaseUrl = action.payload.data.apiBaseUrl;
state.logLevel = action.payload.data.logLevel; state.logLevel = action.payload.data.logLevel;
}; };
const handleUpdateSettingsRejected = (state, action) => { const handleUpdateSettingsRejected = (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to update settings.";
? action.payload.msg
: "Failed to update settings.";
}; };
const settingsSlice = createSlice({ const settingsSlice = createSlice({
name: "settings", name: "settings",
initialState, initialState,
extraReducers: (builder) => { extraReducers: (builder) => {
builder builder
.addCase(getAppSettings.pending, (state) => { .addCase(getAppSettings.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(getAppSettings.fulfilled, handleGetSettingsFulfilled) .addCase(getAppSettings.fulfilled, handleGetSettingsFulfilled)
.addCase(getAppSettings.rejected, handleGetSettingsRejected); .addCase(getAppSettings.rejected, handleGetSettingsRejected);
builder builder
.addCase(updateAppSettings.pending, (state) => { .addCase(updateAppSettings.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(updateAppSettings.fulfilled, handleUpdateSettingsFulfilled) .addCase(updateAppSettings.fulfilled, handleUpdateSettingsFulfilled)
.addCase(updateAppSettings.rejected, handleUpdateSettingsRejected); .addCase(updateAppSettings.rejected, handleUpdateSettingsRejected);
}, },
}); });
export default settingsSlice.reducer; export default settingsSlice.reducer;
+40 -45
View File
@@ -3,54 +3,49 @@ import { createSlice } from "@reduxjs/toolkit";
// Initial state for UI settings. // Initial state for UI settings.
// Add more settings as needed (e.g., theme preferences, user settings) // Add more settings as needed (e.g., theme preferences, user settings)
const initialState = { const initialState = {
monitors: { monitors: {
rowsPerPage: 10, rowsPerPage: 10,
}, },
team: { team: {
rowsPerPage: 5, rowsPerPage: 5,
}, },
maintenance: { maintenance: {
rowsPerPage: 5, rowsPerPage: 5,
}, },
sidebar: { sidebar: {
collapsed: false, collapsed: false,
}, },
mode: "light", mode: "light",
greeting: { index: 0, lastUpdate: null }, greeting: { index: 0, lastUpdate: null },
timezone: "America/Toronto", timezone: "America/Toronto",
}; };
const uiSlice = createSlice({ const uiSlice = createSlice({
name: "ui", name: "ui",
initialState, initialState,
reducers: { reducers: {
setRowsPerPage: (state, action) => { setRowsPerPage: (state, action) => {
const { table, value } = action.payload; const { table, value } = action.payload;
if (state[table]) { if (state[table]) {
state[table].rowsPerPage = value; state[table].rowsPerPage = value;
} }
}, },
toggleSidebar: (state) => { toggleSidebar: (state) => {
state.sidebar.collapsed = !state.sidebar.collapsed; state.sidebar.collapsed = !state.sidebar.collapsed;
}, },
setMode: (state, action) => { setMode: (state, action) => {
state.mode = action.payload; state.mode = action.payload;
}, },
setGreeting(state, action) { setGreeting(state, action) {
state.greeting.index = action.payload.index; state.greeting.index = action.payload.index;
state.greeting.lastUpdate = action.payload.lastUpdate; state.greeting.lastUpdate = action.payload.lastUpdate;
}, },
setTimezone(state, action) { setTimezone(state, action) {
state.timezone = action.payload.timezone; state.timezone = action.payload.timezone;
}, },
}, },
}); });
export default uiSlice.reducer; export default uiSlice.reducer;
export const { export const { setRowsPerPage, toggleSidebar, setMode, setGreeting, setTimezone } =
setRowsPerPage, uiSlice.actions;
toggleSidebar,
setMode,
setGreeting,
setTimezone,
} = uiSlice.actions;
@@ -2,447 +2,442 @@ import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { jwtDecode } from "jwt-decode"; import { jwtDecode } from "jwt-decode";
import { networkService } from "../../main"; import { networkService } from "../../main";
const initialState = { const initialState = {
isLoading: false, isLoading: false,
monitorsSummary: [], monitorsSummary: [],
success: null, success: null,
msg: null, msg: null,
}; };
export const createUptimeMonitor = createAsyncThunk( export const createUptimeMonitor = createAsyncThunk(
"monitors/createMonitor", "monitors/createMonitor",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitor } = data; const { authToken, monitor } = data;
const res = await networkService.createMonitor({ const res = await networkService.createMonitor({
authToken: authToken, authToken: authToken,
monitor: monitor, monitor: monitor,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const checkEndpointResolution = createAsyncThunk( export const checkEndpointResolution = createAsyncThunk(
"monitors/checkEndpoint", "monitors/checkEndpoint",
async(data, thunkApi) => { async (data, thunkApi) => {
try{ try {
const { authToken, monitorURL } = data; const { authToken, monitorURL } = data;
const res = await networkService.checkEndpointResolution({ const res = await networkService.checkEndpointResolution({
authToken: authToken, authToken: authToken,
monitorURL: monitorURL, monitorURL: monitorURL,
}) })
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
) )
export const getUptimeMonitorById = createAsyncThunk( export const getUptimeMonitorById = createAsyncThunk(
"monitors/getMonitorById", "monitors/getMonitorById",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitorId } = data; const { authToken, monitorId } = data;
const res = await networkService.getMonitorById({ const res = await networkService.getMonitorById({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const getUptimeMonitorsByTeamId = createAsyncThunk( export const getUptimeMonitorsByTeamId = createAsyncThunk(
"monitors/getMonitorsByTeamId", "monitors/getMonitorsByTeamId",
async (token, thunkApi) => { async (token, thunkApi) => {
const user = jwtDecode(token); const user = jwtDecode(token);
try { try {
const res = await networkService.getMonitorsAndSummaryByTeamId({ const res = await networkService.getMonitorsAndSummaryByTeamId({
authToken: token, authToken: token,
teamId: user.teamId, teamId: user.teamId,
types: ["http", "ping"], types: ["http", "ping"],
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const updateUptimeMonitor = createAsyncThunk( export const updateUptimeMonitor = createAsyncThunk(
"monitors/updateMonitor", "monitors/updateMonitor",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitor } = data; const { authToken, monitor } = data;
const updatedFields = { const updatedFields = {
name: monitor.name, name: monitor.name,
description: monitor.description, description: monitor.description,
interval: monitor.interval, interval: monitor.interval,
notifications: monitor.notifications, notifications: monitor.notifications,
}; };
const res = await networkService.updateMonitor({ const res = await networkService.updateMonitor({
authToken: authToken, authToken: authToken,
monitorId: monitor._id, monitorId: monitor._id,
updatedFields: updatedFields, updatedFields: updatedFields,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const deleteUptimeMonitor = createAsyncThunk( export const deleteUptimeMonitor = createAsyncThunk(
"monitors/deleteMonitor", "monitors/deleteMonitor",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitor } = data; const { authToken, monitor } = data;
const res = await networkService.deleteMonitorById({ const res = await networkService.deleteMonitorById({
authToken: authToken, authToken: authToken,
monitorId: monitor._id, monitorId: monitor._id,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const pauseUptimeMonitor = createAsyncThunk( export const pauseUptimeMonitor = createAsyncThunk(
"monitors/pauseMonitor", "monitors/pauseMonitor",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, monitorId } = data; const { authToken, monitorId } = data;
const res = await networkService.pauseMonitorById({ const res = await networkService.pauseMonitorById({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const deleteMonitorChecksByTeamId = createAsyncThunk( export const deleteMonitorChecksByTeamId = createAsyncThunk(
"monitors/deleteChecksByTeamId", "monitors/deleteChecksByTeamId",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken, teamId } = data; const { authToken, teamId } = data;
const res = await networkService.deleteChecksByTeamId({ const res = await networkService.deleteChecksByTeamId({
authToken: authToken, authToken: authToken,
teamId: teamId, teamId: teamId,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const addDemoMonitors = createAsyncThunk( export const addDemoMonitors = createAsyncThunk(
"monitors/addDemoMonitors", "monitors/addDemoMonitors",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken } = data; const { authToken } = data;
const res = await networkService.addDemoMonitors({ const res = await networkService.addDemoMonitors({
authToken: authToken, authToken: authToken,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
export const deleteAllMonitors = createAsyncThunk( export const deleteAllMonitors = createAsyncThunk(
"monitors/deleteAllMonitors", "monitors/deleteAllMonitors",
async (data, thunkApi) => { async (data, thunkApi) => {
try { try {
const { authToken } = data; const { authToken } = data;
const res = await networkService.deleteAllMonitors({ const res = await networkService.deleteAllMonitors({
authToken: authToken, authToken: authToken,
}); });
return res.data; return res.data;
} catch (error) { } catch (error) {
if (error.response && error.response.data) { if (error.response && error.response.data) {
return thunkApi.rejectWithValue(error.response.data); return thunkApi.rejectWithValue(error.response.data);
} }
const payload = { const payload = {
status: false, status: false,
msg: error.message ? error.message : "Unknown error", msg: error.message ? error.message : "Unknown error",
}; };
return thunkApi.rejectWithValue(payload); return thunkApi.rejectWithValue(payload);
} }
} }
); );
const uptimeMonitorsSlice = createSlice({ const uptimeMonitorsSlice = createSlice({
name: "uptimeMonitors", name: "uptimeMonitors",
initialState, initialState,
reducers: { reducers: {
clearUptimeMonitorState: (state) => { clearUptimeMonitorState: (state) => {
state.isLoading = false; state.isLoading = false;
state.monitorsSummary = []; state.monitorsSummary = [];
state.success = null; state.success = null;
state.msg = null; state.msg = null;
}, },
}, },
extraReducers: (builder) => { extraReducers: (builder) => {
builder builder
// ***************************************************** // *****************************************************
// Monitors by teamId // Monitors by teamId
// ***************************************************** // *****************************************************
.addCase(getUptimeMonitorsByTeamId.pending, (state) => { .addCase(getUptimeMonitorsByTeamId.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(getUptimeMonitorsByTeamId.fulfilled, (state, action) => { .addCase(getUptimeMonitorsByTeamId.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.msg; state.success = action.payload.msg;
state.monitorsSummary = action.payload.data; state.monitorsSummary = action.payload.data;
}) })
.addCase(getUptimeMonitorsByTeamId.rejected, (state, action) => { .addCase(getUptimeMonitorsByTeamId.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Getting uptime monitors failed"; : "Getting uptime monitors failed";
}) })
// ***************************************************** // *****************************************************
// Create Monitor // Create Monitor
// ***************************************************** // *****************************************************
.addCase(createUptimeMonitor.pending, (state) => { .addCase(createUptimeMonitor.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(createUptimeMonitor.fulfilled, (state, action) => { .addCase(createUptimeMonitor.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(createUptimeMonitor.rejected, (state, action) => { .addCase(createUptimeMonitor.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to create uptime monitor"; : "Failed to create uptime monitor";
}) })
// ***************************************************** // *****************************************************
// Resolve Endpoint // Resolve Endpoint
// ***************************************************** // *****************************************************
.addCase(checkEndpointResolution.pending, (state) => { .addCase(checkEndpointResolution.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(checkEndpointResolution.fulfilled, (state, action) => { .addCase(checkEndpointResolution.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(checkEndpointResolution.rejected, (state, action) => { .addCase(checkEndpointResolution.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to check endpoint resolution"; : "Failed to check endpoint resolution";
}) })
// ***************************************************** // *****************************************************
// Get Monitor By Id // Get Monitor By Id
// ***************************************************** // *****************************************************
.addCase(getUptimeMonitorById.pending, (state) => { .addCase(getUptimeMonitorById.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(getUptimeMonitorById.fulfilled, (state, action) => { .addCase(getUptimeMonitorById.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(getUptimeMonitorById.rejected, (state, action) => { .addCase(getUptimeMonitorById.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to get uptime monitor";
? action.payload.msg })
: "Failed to get uptime monitor"; // *****************************************************
}) // update Monitor
// ***************************************************** // *****************************************************
// update Monitor .addCase(updateUptimeMonitor.pending, (state) => {
// ***************************************************** state.isLoading = true;
.addCase(updateUptimeMonitor.pending, (state) => { })
state.isLoading = true; .addCase(updateUptimeMonitor.fulfilled, (state, action) => {
}) state.isLoading = false;
.addCase(updateUptimeMonitor.fulfilled, (state, action) => { state.success = action.payload.success;
state.isLoading = false; state.msg = action.payload.msg;
state.success = action.payload.success; })
state.msg = action.payload.msg; .addCase(updateUptimeMonitor.rejected, (state, action) => {
}) state.isLoading = false;
.addCase(updateUptimeMonitor.rejected, (state, action) => { state.success = false;
state.isLoading = false; state.msg = action.payload
state.success = false; ? action.payload.msg
state.msg = action.payload : "Failed to update uptime monitor";
? action.payload.msg })
: "Failed to update uptime monitor";
})
// ***************************************************** // *****************************************************
// Delete Monitor // Delete Monitor
// ***************************************************** // *****************************************************
.addCase(deleteUptimeMonitor.pending, (state) => { .addCase(deleteUptimeMonitor.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(deleteUptimeMonitor.fulfilled, (state, action) => { .addCase(deleteUptimeMonitor.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(deleteUptimeMonitor.rejected, (state, action) => { .addCase(deleteUptimeMonitor.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to delete uptime monitor"; : "Failed to delete uptime monitor";
}) })
// ***************************************************** // *****************************************************
// Delete Monitor checks by Team ID // Delete Monitor checks by Team ID
// ***************************************************** // *****************************************************
.addCase(deleteMonitorChecksByTeamId.pending, (state) => { .addCase(deleteMonitorChecksByTeamId.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(deleteMonitorChecksByTeamId.fulfilled, (state, action) => { .addCase(deleteMonitorChecksByTeamId.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(deleteMonitorChecksByTeamId.rejected, (state, action) => { .addCase(deleteMonitorChecksByTeamId.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to delete monitor checks"; : "Failed to delete monitor checks";
}) })
// ***************************************************** // *****************************************************
// Pause Monitor // Pause Monitor
// ***************************************************** // *****************************************************
.addCase(pauseUptimeMonitor.pending, (state) => { .addCase(pauseUptimeMonitor.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(pauseUptimeMonitor.fulfilled, (state, action) => { .addCase(pauseUptimeMonitor.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(pauseUptimeMonitor.rejected, (state, action) => { .addCase(pauseUptimeMonitor.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to pause uptime monitor"; : "Failed to pause uptime monitor";
}) })
// ***************************************************** // *****************************************************
// Add Demo Monitors // Add Demo Monitors
// ***************************************************** // *****************************************************
.addCase(addDemoMonitors.pending, (state) => { .addCase(addDemoMonitors.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(addDemoMonitors.fulfilled, (state, action) => { .addCase(addDemoMonitors.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(addDemoMonitors.rejected, (state, action) => { .addCase(addDemoMonitors.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload
? action.payload.msg ? action.payload.msg
: "Failed to add demo uptime monitors"; : "Failed to add demo uptime monitors";
}) })
// ***************************************************** // *****************************************************
// Delete all Monitors // Delete all Monitors
// ***************************************************** // *****************************************************
.addCase(deleteAllMonitors.pending, (state) => { .addCase(deleteAllMonitors.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(deleteAllMonitors.fulfilled, (state, action) => { .addCase(deleteAllMonitors.fulfilled, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = action.payload.success; state.success = action.payload.success;
state.msg = action.payload.msg; state.msg = action.payload.msg;
}) })
.addCase(deleteAllMonitors.rejected, (state, action) => { .addCase(deleteAllMonitors.rejected, (state, action) => {
state.isLoading = false; state.isLoading = false;
state.success = false; state.success = false;
state.msg = action.payload state.msg = action.payload ? action.payload.msg : "Failed to delete all monitors";
? action.payload.msg });
: "Failed to delete all monitors"; },
});
},
}); });
export const { setUptimeMonitors, clearUptimeMonitorState } = export const { setUptimeMonitors, clearUptimeMonitorState } = uptimeMonitorsSlice.actions;
uptimeMonitorsSlice.actions;
export default uptimeMonitorsSlice.reducer; export default uptimeMonitorsSlice.reducer;
+25 -20
View File
@@ -5,28 +5,33 @@ import { logger } from "../Utils/Logger";
import { networkService } from "../main"; import { networkService } from "../main";
const withAdminCheck = (WrappedComponent) => { const withAdminCheck = (WrappedComponent) => {
const WithAdminCheck = (props) => { const WithAdminCheck = (props) => {
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
networkService networkService
.doesSuperAdminExist() .doesSuperAdminExist()
.then((response) => { .then((response) => {
if (response.data.data === true) { if (response.data.data === true) {
navigate("/login"); navigate("/login");
} }
}) })
.catch((error) => { .catch((error) => {
logger.error(error); logger.error(error);
}); });
}, [navigate]); }, [navigate]);
return <WrappedComponent {...props} isSuperAdmin={true} />; return (
}; <WrappedComponent
const wrappedComponentName = {...props}
WrappedComponent.displayName || WrappedComponent.name || "Component"; isSuperAdmin={true}
WithAdminCheck.displayName = `WithAdminCheck(${wrappedComponentName})`; />
);
};
const wrappedComponentName =
WrappedComponent.displayName || WrappedComponent.name || "Component";
WithAdminCheck.displayName = `WithAdminCheck(${wrappedComponentName})`;
return WithAdminCheck; return WithAdminCheck;
}; };
export default withAdminCheck; export default withAdminCheck;
+16 -11
View File
@@ -1,20 +1,25 @@
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
const withAdminProp = (WrappedComponent) => { const withAdminProp = (WrappedComponent) => {
const WithAdminProp = (props) => { const WithAdminProp = (props) => {
const { user } = useSelector((state) => state.auth); const { user } = useSelector((state) => state.auth);
const isAdmin = const isAdmin =
(user?.role?.includes("admin") ?? false) || (user?.role?.includes("admin") ?? false) ||
(user?.role?.includes("superadmin") ?? false); (user?.role?.includes("superadmin") ?? false);
return <WrappedComponent {...props} isAdmin={isAdmin} />; return (
}; <WrappedComponent
{...props}
isAdmin={isAdmin}
/>
);
};
const wrappedComponentName = const wrappedComponentName =
WrappedComponent.displayName || WrappedComponent.name || "Component"; WrappedComponent.displayName || WrappedComponent.name || "Component";
WithAdminProp.displayName = `WithAdminProp(${wrappedComponentName})`; WithAdminProp.displayName = `WithAdminProp(${wrappedComponentName})`;
return WithAdminProp; return WithAdminProp;
}; };
export default withAdminProp; export default withAdminProp;
+24 -24
View File
@@ -1,38 +1,38 @@
.home-layout { .home-layout {
position: relative; position: relative;
min-height: 100vh; min-height: 100vh;
max-width: 1400px; max-width: 1400px;
margin: 0 auto; margin: 0 auto;
padding: var(--env-var-spacing-2); padding: var(--env-var-spacing-2);
} }
.home-layout aside { .home-layout aside {
position: sticky; position: sticky;
top: var(--env-var-spacing-2); top: var(--env-var-spacing-2);
left: 0; left: 0;
height: calc(100vh - var(--env-var-spacing-2) * 2); height: calc(100vh - var(--env-var-spacing-2) * 2);
max-width: var(--env-var-side-bar-width); max-width: var(--env-var-side-bar-width);
} }
.home-layout > div { .home-layout > div {
min-height: calc(100vh - var(--env-var-spacing-2) * 2); min-height: calc(100vh - var(--env-var-spacing-2) * 2);
flex: 1; flex: 1;
} }
.home-layout > div:has(> [class*="fallback__"]) .background-pattern-svg { .home-layout > div:has(> [class*="fallback__"]) .background-pattern-svg {
position: absolute; position: absolute;
top: 0; top: 0;
left: 50%; left: 50%;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);
z-index: 0; z-index: 0;
width: 100%; width: 100%;
max-width: 800px; max-width: 800px;
height: 100%; height: 100%;
max-height: 800px; max-height: 800px;
background-position: center; background-position: center;
background-size: cover; background-size: cover;
background-repeat: no-repeat; background-repeat: no-repeat;
} }
+10 -6
View File
@@ -5,12 +5,16 @@ import { Stack } from "@mui/material";
import "./index.css"; import "./index.css";
const HomeLayout = () => { const HomeLayout = () => {
return ( return (
<Stack className="home-layout" flexDirection="row" gap={14}> <Stack
<Sidebar /> className="home-layout"
<Outlet /> flexDirection="row"
</Stack> gap={14}
); >
<Sidebar />
<Outlet />
</Stack>
);
}; };
export default HomeLayout; export default HomeLayout;
+11 -11
View File
@@ -4,35 +4,35 @@
.account button, .account button,
.account td, .account td,
.account .MuiSelect-select { .account .MuiSelect-select {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.account h1.MuiTypography-root { .account h1.MuiTypography-root {
font-weight: 600; font-weight: 600;
} }
.account .MuiTabPanel-root { .account .MuiTabPanel-root {
padding: 0; padding: 0;
margin-top: 50px; margin-top: 50px;
} }
.account button:not(.MuiIconButton-root) { .account button:not(.MuiIconButton-root) {
height: 34px; height: 34px;
} }
.account .field { .account .field {
flex: 1; flex: 1;
} }
#modal-delete-account, #modal-delete-account,
#modal-edit-org-name, #modal-edit-org-name,
#modal-invite-member { #modal-invite-member {
font-size: var(--env-var-font-size-large); font-size: var(--env-var-font-size-large);
} }
.account .MuiStack-root:has(span.MuiTypography-root.input-error) { .account .MuiStack-root:has(span.MuiTypography-root.input-error) {
position: relative; position: relative;
} }
.account:not(:has(#modal-invite-member)) span.MuiTypography-root.input-error { .account:not(:has(#modal-invite-member)) span.MuiTypography-root.input-error {
position: absolute; position: absolute;
top: 100%; top: 100%;
} }
.account .MuiTableBody-root .MuiTableCell-root { .account .MuiTableBody-root .MuiTableCell-root {
padding: var(--env-var-spacing-1-plus) var(--env-var-spacing-2); padding: var(--env-var-spacing-1-plus) var(--env-var-spacing-2);
} }
+69 -66
View File
@@ -16,78 +16,81 @@ import "./index.css";
*/ */
const Account = ({ open = "profile" }) => { const Account = ({ open = "profile" }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const tab = open; const tab = open;
const handleTabChange = (event, newTab) => { const handleTabChange = (event, newTab) => {
navigate(`/account/${newTab}`); navigate(`/account/${newTab}`);
}; };
const { user } = useSelector((state) => state.auth); const { user } = useSelector((state) => state.auth);
const requiredRoles = ["superadmin", "admin"]; const requiredRoles = ["superadmin", "admin"];
let tabList = ["Profile", "Password", "Team"]; let tabList = ["Profile", "Password", "Team"];
const hideTeams = !requiredRoles.some((role) => user.role.includes(role)); const hideTeams = !requiredRoles.some((role) => user.role.includes(role));
if (hideTeams) { if (hideTeams) {
tabList = ["Profile", "Password"]; tabList = ["Profile", "Password"];
} }
// Remove password for demo // Remove password for demo
if (user.role.includes("demo")) { if (user.role.includes("demo")) {
tabList = ["Profile"]; tabList = ["Profile"];
} }
return ( return (
<Box <Box
className="account" className="account"
px={theme.spacing(20)} px={theme.spacing(20)}
py={theme.spacing(12)} py={theme.spacing(12)}
border={1} border={1}
borderColor={theme.palette.border.light} borderColor={theme.palette.border.light}
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
backgroundColor={theme.palette.background.main} backgroundColor={theme.palette.background.main}
> >
<TabContext value={tab}> <TabContext value={tab}>
<Box <Box
sx={{ sx={{
borderBottom: 1, borderBottom: 1,
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
"& .MuiTabs-root": { height: "fit-content", minHeight: "0" }, "& .MuiTabs-root": { height: "fit-content", minHeight: "0" },
}} }}
> >
<TabList onChange={handleTabChange} aria-label="account tabs"> <TabList
{tabList.map((label, index) => ( onChange={handleTabChange}
<Tab aria-label="account tabs"
label={label} >
key={index} {tabList.map((label, index) => (
value={label.toLowerCase()} <Tab
sx={{ label={label}
fontSize: 13, key={index}
color: theme.palette.text.tertiary, value={label.toLowerCase()}
textTransform: "none", sx={{
minWidth: "fit-content", fontSize: 13,
minHeight: 0, color: theme.palette.text.tertiary,
paddingLeft: 0, textTransform: "none",
paddingY: theme.spacing(4), minWidth: "fit-content",
fontWeight: 400, minHeight: 0,
marginRight: theme.spacing(8), paddingLeft: 0,
"&:focus": { paddingY: theme.spacing(4),
outline: "none", fontWeight: 400,
}, marginRight: theme.spacing(8),
}} "&:focus": {
/> outline: "none",
))} },
</TabList> }}
</Box> />
<ProfilePanel /> ))}
{user.role.includes("superadmin") && <PasswordPanel />} </TabList>
{!hideTeams && <TeamPanel />} </Box>
</TabContext> <ProfilePanel />
</Box> {user.role.includes("superadmin") && <PasswordPanel />}
); {!hideTeams && <TeamPanel />}
</TabContext>
</Box>
);
}; };
Account.propTypes = { Account.propTypes = {
open: PropTypes.oneOf(["profile", "password", "team"]), open: PropTypes.oneOf(["profile", "password", "team"]),
}; };
export default Account; export default Account;
+234 -236
View File
@@ -9,257 +9,255 @@ import PropTypes from "prop-types";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { ConfigBox } from "../Settings/styled"; import { ConfigBox } from "../Settings/styled";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import { import { getAppSettings, updateAppSettings } from "../../Features/Settings/settingsSlice";
getAppSettings,
updateAppSettings,
} from "../../Features/Settings/settingsSlice";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import Select from "../../Components/Inputs/Select"; import Select from "../../Components/Inputs/Select";
const AdvancedSettings = ({ isAdmin }) => { const AdvancedSettings = ({ isAdmin }) => {
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
if (!isAdmin) { if (!isAdmin) {
navigate("/"); navigate("/");
} }
}, [navigate, isAdmin]); }, [navigate, isAdmin]);
const theme = useTheme(); const theme = useTheme();
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const dispatch = useDispatch(); const dispatch = useDispatch();
const settings = useSelector((state) => state.settings); const settings = useSelector((state) => state.settings);
const [localSettings, setLocalSettings] = useState({ const [localSettings, setLocalSettings] = useState({
apiBaseUrl: "", apiBaseUrl: "",
logLevel: "debug", logLevel: "debug",
systemEmailHost: "", systemEmailHost: "",
systemEmailPort: "", systemEmailPort: "",
systemEmailAddress: "", systemEmailAddress: "",
systemEmailPassword: "", systemEmailPassword: "",
jwtTTL: "", jwtTTL: "",
dbType: "", dbType: "",
redisHost: "", redisHost: "",
redisPort: "", redisPort: "",
pagespeedApiKey: "", pagespeedApiKey: "",
}); });
useEffect(() => { useEffect(() => {
const getSettings = async () => { const getSettings = async () => {
const action = await dispatch(getAppSettings({ authToken })); const action = await dispatch(getAppSettings({ authToken }));
if (action.payload.success) { if (action.payload.success) {
setLocalSettings(action.payload.data); setLocalSettings(action.payload.data);
} else { } else {
createToast({ body: "Failed to get settings" }); createToast({ body: "Failed to get settings" });
} }
}; };
getSettings(); getSettings();
}, [authToken, dispatch]); }, [authToken, dispatch]);
const logItems = [ const logItems = [
{ _id: 1, name: "none" }, { _id: 1, name: "none" },
{ _id: 2, name: "debug" }, { _id: 2, name: "debug" },
{ _id: 3, name: "error" }, { _id: 3, name: "error" },
{ _id: 4, name: "warn" }, { _id: 4, name: "warn" },
]; ];
const logItemLookup = { const logItemLookup = {
none: 1, none: 1,
debug: 2, debug: 2,
error: 3, error: 3,
warn: 4, warn: 4,
}; };
const handleLogLevel = (e) => { const handleLogLevel = (e) => {
const id = e.target.value; const id = e.target.value;
const newLogLevel = logItems.find((item) => item._id === id).name; const newLogLevel = logItems.find((item) => item._id === id).name;
setLocalSettings({ ...localSettings, logLevel: newLogLevel }); setLocalSettings({ ...localSettings, logLevel: newLogLevel });
}; };
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
setLocalSettings({ ...localSettings, [id]: value }); setLocalSettings({ ...localSettings, [id]: value });
}; };
const handleSave = async () => { const handleSave = async () => {
const action = await dispatch( const action = await dispatch(
updateAppSettings({ settings: localSettings, authToken }) updateAppSettings({ settings: localSettings, authToken })
); );
let body = ""; let body = "";
if (action.payload.success) { if (action.payload.success) {
console.log(action.payload.data); console.log(action.payload.data);
setLocalSettings(action.payload.data); setLocalSettings(action.payload.data);
body = "Settings saved successfully"; body = "Settings saved successfully";
} else { } else {
body = "Failed to save settings"; body = "Failed to save settings";
} }
createToast({ body }); createToast({ body });
}; };
return ( return (
<Box <Box
className="settings" className="settings"
style={{ style={{
paddingBottom: 0, paddingBottom: 0,
}} }}
> >
<Stack <Stack
component="form" component="form"
gap={theme.spacing(12)} gap={theme.spacing(12)}
noValidate noValidate
spellCheck="false" spellCheck="false"
> >
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">Client settings</Typography> <Typography component="h1">Client settings</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Modify client settings here. Modify client settings here.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Field <Field
id="apiBaseUrl" id="apiBaseUrl"
label="API URL Host" label="API URL Host"
value={localSettings.apiBaseUrl} value={localSettings.apiBaseUrl}
onChange={handleChange} onChange={handleChange}
/> />
<Select <Select
id="logLevel" id="logLevel"
label="Log level" label="Log level"
name="logLevel" name="logLevel"
items={logItems} items={logItems}
value={logItemLookup[localSettings.logLevel]} value={logItemLookup[localSettings.logLevel]}
onChange={handleLogLevel} onChange={handleLogLevel}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">Email settings</Typography> <Typography component="h1">Email settings</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Set your host email settings here. These settings are used for Set your host email settings here. These settings are used for sending
sending system emails. system emails.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Field <Field
type="text" type="text"
id="systemEmailHost" id="systemEmailHost"
label="Email host" label="Email host"
name="systemEmailHost" name="systemEmailHost"
value={localSettings.systemEmailHost} value={localSettings.systemEmailHost}
onChange={handleChange} onChange={handleChange}
/> />
<Field <Field
type="number" type="number"
id="systemEmailPort" id="systemEmailPort"
label="System email address" label="System email address"
name="systemEmailPort" name="systemEmailPort"
value={localSettings.systemEmailPort.toString()} value={localSettings.systemEmailPort.toString()}
onChange={handleChange} onChange={handleChange}
/> />
<Field <Field
type="email" type="email"
id="systemEmailAddress" id="systemEmailAddress"
label="System email address" label="System email address"
name="systemEmailAddress" name="systemEmailAddress"
value={localSettings.systemEmailAddress} value={localSettings.systemEmailAddress}
onChange={handleChange} onChange={handleChange}
/> />
<Field <Field
type="text" type="text"
id="systemEmailPassword" id="systemEmailPassword"
label="System email password" label="System email password"
name="systemEmailPassword" name="systemEmailPassword"
value={localSettings.systemEmailPassword} value={localSettings.systemEmailPassword}
onChange={handleChange} onChange={handleChange}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">Server settings</Typography> <Typography component="h1">Server settings</Typography>
<Typography sx={{ mt: theme.spacing(2) }}> <Typography sx={{ mt: theme.spacing(2) }}>
Modify server settings here. Modify server settings here.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(20)}> <Stack gap={theme.spacing(20)}>
<Field <Field
type="text" type="text"
id="jwtTTL" id="jwtTTL"
label="JWT time to live" label="JWT time to live"
name="jwtTTL" name="jwtTTL"
value={localSettings.jwtTTL} value={localSettings.jwtTTL}
onChange={handleChange} onChange={handleChange}
/> />
<Field <Field
type="text" type="text"
id="dbType" id="dbType"
label="Database type" label="Database type"
name="dbType" name="dbType"
value={localSettings.dbType} value={localSettings.dbType}
onChange={handleChange} onChange={handleChange}
/> />
<Field <Field
type="text" type="text"
id="redisHost" id="redisHost"
label="Redis host" label="Redis host"
name="redisHost" name="redisHost"
value={localSettings.redisHost} value={localSettings.redisHost}
onChange={handleChange} onChange={handleChange}
/> />
<Field <Field
type="number" type="number"
id="redisPort" id="redisPort"
label="Redis port" label="Redis port"
name="redisPort" name="redisPort"
value={localSettings.redisPort.toString()} value={localSettings.redisPort.toString()}
onChange={handleChange} onChange={handleChange}
/> />
<Field <Field
type="text" type="text"
id="pagespeedApiKey" id="pagespeedApiKey"
label="PageSpeed API key" label="PageSpeed API key"
name="pagespeedApiKey" name="pagespeedApiKey"
value={localSettings.pagespeedApiKey} value={localSettings.pagespeedApiKey}
onChange={handleChange} onChange={handleChange}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h1">About</Typography> <Typography component="h1">About</Typography>
</Box> </Box>
<Box> <Box>
<Typography component="h2">BlueWave Uptime v1.0.0</Typography> <Typography component="h2">BlueWave Uptime v1.0.0</Typography>
<Typography <Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}>
sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }} Developed by Bluewave Labs.
> </Typography>
Developed by Bluewave Labs. <Link
</Typography> level="secondary"
<Link url="https://github.com/bluewave-labs"
level="secondary" label="https://github.com/bluewave-labs"
url="https://github.com/bluewave-labs" />
label="https://github.com/bluewave-labs" </Box>
/> </ConfigBox>
</Box> <Stack
</ConfigBox> direction="row"
<Stack direction="row" justifyContent="flex-end"> justifyContent="flex-end"
<LoadingButton >
loading={settings.isLoading || settings.authIsLoading} <LoadingButton
variant="contained" loading={settings.isLoading || settings.authIsLoading}
color="primary" variant="contained"
sx={{ px: theme.spacing(12), mt: theme.spacing(20) }} color="primary"
onClick={handleSave} sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
> onClick={handleSave}
Save >
</LoadingButton> Save
</Stack> </LoadingButton>
</Stack> </Stack>
</Box> </Stack>
); </Box>
);
}; };
AdvancedSettings.propTypes = { AdvancedSettings.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
}; };
export default AdvancedSettings; export default AdvancedSettings;
+186 -180
View File
@@ -12,192 +12,198 @@ import Logo from "../../assets/icons/bwu-icon.svg?react";
import "./index.css"; import "./index.css";
const CheckEmail = () => { const CheckEmail = () => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const [email, setEmail] = useState(); const [email, setEmail] = useState();
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
useEffect(() => { useEffect(() => {
setEmail(sessionStorage.getItem("email")); setEmail(sessionStorage.getItem("email"));
}, []); }, []);
// TODO - fix // TODO - fix
const openMail = () => { const openMail = () => {
window.location.href = "mailto:"; window.location.href = "mailto:";
}; };
const toastFail = [ const toastFail = [
{ {
body: "Email not found.", body: "Email not found.",
}, },
{ {
body: "Redirecting in 3...", body: "Redirecting in 3...",
}, },
{ {
body: "Redirecting in 2...", body: "Redirecting in 2...",
}, },
{ {
body: "Redirecting in 1...", body: "Redirecting in 1...",
}, },
]; ];
const resendToken = async () => { const resendToken = async () => {
setDisabled(true); // prevent resent button from being spammed setDisabled(true); // prevent resent button from being spammed
if (!email) { if (!email) {
let index = 0; let index = 0;
const interval = setInterval(() => { const interval = setInterval(() => {
if (index < toastFail.length) { if (index < toastFail.length) {
createToast(toastFail[index]); createToast(toastFail[index]);
index++; index++;
} else { } else {
clearInterval(interval); clearInterval(interval);
navigate("/forgot-password"); navigate("/forgot-password");
} }
}, 1000); }, 1000);
} else { } else {
const form = { email: email }; const form = { email: email };
const action = await dispatch(forgotPassword(form)); const action = await dispatch(forgotPassword(form));
if (action.payload.success) { if (action.payload.success) {
createToast({ createToast({
body: `Instructions sent to ${form.email}.`, body: `Instructions sent to ${form.email}.`,
}); });
setDisabled(false); setDisabled(false);
} else { } else {
if (action.payload) { if (action.payload) {
// dispatch errors // dispatch errors
createToast({ createToast({
body: action.payload.msg, body: action.payload.msg,
}); });
} else { } else {
// unknown errors // unknown errors
createToast({ createToast({
body: "Unknown error.", body: "Unknown error.",
}); });
} }
} }
} }
}; };
const handleNavigate = () => { const handleNavigate = () => {
sessionStorage.removeItem("email"); sessionStorage.removeItem("email");
navigate("/login"); navigate("/login");
}; };
return ( return (
<Stack <Stack
className="check-email-page auth" className="check-email-page auth"
overflow="hidden" overflow="hidden"
sx={{ sx={{
"& h1": { "& h1": {
color: theme.palette.primary.main, color: theme.palette.primary.main,
fontWeight: 600, fontWeight: 600,
fontSize: 22, fontSize: 22,
}, },
"& p": { color: theme.palette.text.accent, fontSize: 13.5 }, "& p": { color: theme.palette.text.accent, fontSize: 13.5 },
"& span": { fontSize: "inherit" }, "& span": { fontSize: "inherit" },
}} }}
> >
<Box <Box
className="background-pattern-svg" className="background-pattern-svg"
sx={{ sx={{
"& svg g g:last-of-type path": { "& svg g g:last-of-type path": {
stroke: theme.palette.border.light, stroke: theme.palette.border.light,
}, },
}} }}
> >
<Background style={{ width: "100%" }} /> <Background style={{ width: "100%" }} />
</Box> </Box>
<Stack <Stack
direction="row" direction="row"
alignItems="center" alignItems="center"
px={theme.spacing(12)} px={theme.spacing(12)}
gap={theme.spacing(4)} gap={theme.spacing(4)}
> >
<Logo style={{ borderRadius: theme.shape.borderRadius }} /> <Logo style={{ borderRadius: theme.shape.borderRadius }} />
<Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography> <Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography>
</Stack> </Stack>
<Stack <Stack
width="100%" width="100%"
maxWidth={600} maxWidth={600}
flex={1} flex={1}
justifyContent="center" justifyContent="center"
px={{ xs: theme.spacing(12), lg: theme.spacing(20) }} px={{ xs: theme.spacing(12), lg: theme.spacing(20) }}
pb={theme.spacing(20)} pb={theme.spacing(20)}
mx="auto" mx="auto"
sx={{ sx={{
"& > .MuiStack-root": { "& > .MuiStack-root": {
border: 1, border: 1,
borderRadius: theme.spacing(5), borderRadius: theme.spacing(5),
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
padding: { padding: {
xs: theme.spacing(12), xs: theme.spacing(12),
sm: theme.spacing(20), sm: theme.spacing(20),
}, },
}, },
}} }}
> >
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(10) }} gap={{ xs: theme.spacing(8), sm: theme.spacing(10) }}
alignItems="center" alignItems="center"
textAlign="center" textAlign="center"
> >
<Box> <Box>
<IconBox> <IconBox>
<EmailIcon alt="email icon" /> <EmailIcon alt="email icon" />
</IconBox> </IconBox>
<Typography component="h1">Check your email</Typography> <Typography component="h1">Check your email</Typography>
<Typography> <Typography>
We sent a password reset link to{" "} We sent a password reset link to{" "}
<Typography className="email-sent-to" component="span"> <Typography
{email || "username@email.com"} className="email-sent-to"
</Typography> component="span"
</Typography> >
</Box> {email || "username@email.com"}
<Button </Typography>
variant="contained" </Typography>
color="primary" </Box>
onClick={openMail} <Button
sx={{ variant="contained"
width: "100%", color="primary"
maxWidth: 400, onClick={openMail}
}} sx={{
> width: "100%",
Open email app maxWidth: 400,
</Button> }}
<Typography sx={{ alignSelf: "center", mt: theme.spacing(6) }}> >
Didn&apos;t receive the email?{" "} Open email app
<Typography </Button>
component="span" <Typography sx={{ alignSelf: "center", mt: theme.spacing(6) }}>
onClick={resendToken} Didn&apos;t receive the email?{" "}
sx={{ <Typography
color: theme.palette.primary.main, component="span"
userSelect: "none", onClick={resendToken}
pointerEvents: disabled ? "none" : "auto", sx={{
cursor: disabled ? "default" : "pointer", color: theme.palette.primary.main,
opacity: disabled ? 0.5 : 1, userSelect: "none",
}} pointerEvents: disabled ? "none" : "auto",
> cursor: disabled ? "default" : "pointer",
Click to resend opacity: disabled ? 0.5 : 1,
</Typography> }}
</Typography> >
</Stack> Click to resend
</Stack> </Typography>
<Box textAlign="center" p={theme.spacing(12)}> </Typography>
<Typography display="inline-block">Go back to —</Typography> </Stack>
<Typography </Stack>
component="span" <Box
ml={theme.spacing(2)} textAlign="center"
color={theme.palette.primary.main} p={theme.spacing(12)}
onClick={handleNavigate} >
sx={{ userSelect: "none" }} <Typography display="inline-block">Go back to —</Typography>
> <Typography
Log In component="span"
</Typography> ml={theme.spacing(2)}
</Box> color={theme.palette.primary.main}
</Stack> onClick={handleNavigate}
); sx={{ userSelect: "none" }}
>
Log In
</Typography>
</Box>
</Stack>
);
}; };
export default CheckEmail; export default CheckEmail;
+178 -180
View File
@@ -15,196 +15,194 @@ import LoadingButton from "@mui/lab/LoadingButton";
import "./index.css"; import "./index.css";
const ForgotPassword = () => { const ForgotPassword = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const theme = useTheme(); const theme = useTheme();
const { isLoading } = useSelector((state) => state.auth); const { isLoading } = useSelector((state) => state.auth);
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [form, setForm] = useState({ const [form, setForm] = useState({
email: "", email: "",
}); });
useEffect(() => { useEffect(() => {
const email = sessionStorage.getItem("email"); const email = sessionStorage.getItem("email");
email && setForm({ email: sessionStorage.getItem("email") }); email && setForm({ email: sessionStorage.getItem("email") });
}, []); }, []);
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const { error } = credentials.validate(form, { abortEarly: false }); const { error } = credentials.validate(form, { abortEarly: false });
if (error) { if (error) {
// validation errors // validation errors
const err = const err =
error.details && error.details.length > 0 error.details && error.details.length > 0
? error.details[0].message ? error.details[0].message
: "Error validating data."; : "Error validating data.";
setErrors({ email: err }); setErrors({ email: err });
createToast({ createToast({
body: err, body: err,
}); });
} else { } else {
const action = await dispatch(forgotPassword(form)); const action = await dispatch(forgotPassword(form));
if (action.payload.success) { if (action.payload.success) {
sessionStorage.setItem("email", form.email); sessionStorage.setItem("email", form.email);
navigate("/check-email"); navigate("/check-email");
createToast({ createToast({
body: `Instructions sent to ${form.email}.`, body: `Instructions sent to ${form.email}.`,
}); });
} else { } else {
if (action.payload) { if (action.payload) {
// dispatch errors // dispatch errors
createToast({ createToast({
body: action.payload.msg, body: action.payload.msg,
}); });
} else { } else {
// unknown errors // unknown errors
createToast({ createToast({
body: "Unknown error.", body: "Unknown error.",
}); });
} }
} }
} }
}; };
const handleChange = (event) => { const handleChange = (event) => {
const { value } = event.target; const { value } = event.target;
setForm({ email: value }); setForm({ email: value });
const { error } = credentials.validate( const { error } = credentials.validate({ email: value }, { abortEarly: false });
{ email: value },
{ abortEarly: false }
);
if (error) setErrors({ email: error.details[0].message }); if (error) setErrors({ email: error.details[0].message });
else delete errors.email; else delete errors.email;
}; };
const handleNavigate = () => { const handleNavigate = () => {
sessionStorage.removeItem("email"); sessionStorage.removeItem("email");
navigate("/login"); navigate("/login");
}; };
return ( return (
<Stack <Stack
className="forgot-password-page auth" className="forgot-password-page auth"
overflow="hidden" overflow="hidden"
sx={{ sx={{
"& h1": { "& h1": {
color: theme.palette.primary.main, color: theme.palette.primary.main,
fontWeight: 600, fontWeight: 600,
fontSize: 21, fontSize: 21,
}, },
"& p": { "& p": {
fontSize: 14, fontSize: 14,
color: theme.palette.text.accent, color: theme.palette.text.accent,
}, },
}} }}
> >
<Box <Box
className="background-pattern-svg" className="background-pattern-svg"
sx={{ sx={{
"& svg g g:last-of-type path": { "& svg g g:last-of-type path": {
stroke: theme.palette.border.light, stroke: theme.palette.border.light,
}, },
}} }}
> >
<Background style={{ width: "100%" }} /> <Background style={{ width: "100%" }} />
</Box> </Box>
<Stack <Stack
direction="row" direction="row"
alignItems="center" alignItems="center"
px={theme.spacing(12)} px={theme.spacing(12)}
gap={theme.spacing(4)} gap={theme.spacing(4)}
> >
<Logo style={{ borderRadius: theme.shape.borderRadius }} /> <Logo style={{ borderRadius: theme.shape.borderRadius }} />
<Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography> <Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography>
</Stack> </Stack>
<Stack <Stack
width="100%" width="100%"
maxWidth={600} maxWidth={600}
flex={1} flex={1}
justifyContent="center" justifyContent="center"
px={{ xs: theme.spacing(12), lg: theme.spacing(20) }} px={{ xs: theme.spacing(12), lg: theme.spacing(20) }}
pb={theme.spacing(20)} pb={theme.spacing(20)}
mx="auto" mx="auto"
sx={{ sx={{
"& > .MuiStack-root": { "& > .MuiStack-root": {
border: 1, border: 1,
borderRadius: theme.spacing(5), borderRadius: theme.spacing(5),
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
padding: { padding: {
xs: theme.spacing(12), xs: theme.spacing(12),
sm: theme.spacing(20), sm: theme.spacing(20),
}, },
}, },
}} }}
> >
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }}
alignItems="center" alignItems="center"
textAlign="center" textAlign="center"
> >
<Box> <Box>
<IconBox> <IconBox>
<Key alt="password key icon" /> <Key alt="password key icon" />
</IconBox> </IconBox>
<Typography component="h1">Forgot password?</Typography> <Typography component="h1">Forgot password?</Typography>
<Typography> <Typography>No worries, we&apos;ll send you reset instructions.</Typography>
No worries, we&apos;ll send you reset instructions. </Box>
</Typography> <Box
</Box> component="form"
<Box width="95%"
component="form" textAlign="left"
width="95%" noValidate
textAlign="left" spellCheck={false}
noValidate onSubmit={handleSubmit}
spellCheck={false} >
onSubmit={handleSubmit} <Field
> type="email"
<Field id="forgot-password-email-input"
type="email" label="Email"
id="forgot-password-email-input" isRequired={true}
label="Email" placeholder="Enter your email"
isRequired={true} value={form.email}
placeholder="Enter your email" onChange={handleChange}
value={form.email} error={errors.email}
onChange={handleChange} />
error={errors.email} <LoadingButton
/> variant="contained"
<LoadingButton color="primary"
variant="contained" loading={isLoading}
color="primary" disabled={errors.email !== undefined}
loading={isLoading} onClick={handleSubmit}
disabled={errors.email !== undefined} sx={{
onClick={handleSubmit} width: "100%",
sx={{ mt: theme.spacing(15),
width: "100%", }}
mt: theme.spacing(15), >
}} Send instructions
> </LoadingButton>
Send instructions </Box>
</LoadingButton> </Stack>
</Box> </Stack>
</Stack> <Box
</Stack> textAlign="center"
<Box textAlign="center" p={theme.spacing(12)}> p={theme.spacing(12)}
<Typography display="inline-block">Go back to —</Typography> >
<Typography <Typography display="inline-block">Go back to —</Typography>
component="span" <Typography
color={theme.palette.primary.main} component="span"
ml={theme.spacing(2)} color={theme.palette.primary.main}
onClick={handleNavigate} ml={theme.spacing(2)}
sx={{ userSelect: "none" }} onClick={handleNavigate}
> sx={{ userSelect: "none" }}
Log In >
</Typography> Log In
</Box> </Typography>
</Stack> </Box>
); </Stack>
);
}; };
export default ForgotPassword; export default ForgotPassword;
+460 -443
View File
@@ -25,85 +25,85 @@ const DEMO = import.meta.env.VITE_APP_DEMO;
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const LandingPage = ({ onContinue }) => { const LandingPage = ({ onContinue }) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<> <>
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }}
alignItems="center" alignItems="center"
textAlign="center" textAlign="center"
> >
<Box> <Box>
<Typography component="h1">Log In</Typography> <Typography component="h1">Log In</Typography>
<Typography>We are pleased to see you again!</Typography> <Typography>We are pleased to see you again!</Typography>
</Box> </Box>
<Box width="100%"> <Box width="100%">
<Button <Button
variant="outlined" variant="outlined"
color="info" color="info"
onClick={onContinue} onClick={onContinue}
sx={{ sx={{
width: "100%", width: "100%",
"& svg": { "& svg": {
mr: theme.spacing(4), mr: theme.spacing(4),
"& path": { "& path": {
stroke: theme.palette.other.icon, stroke: theme.palette.other.icon,
}, },
}, },
}} }}
> >
<Mail /> <Mail />
Continue with Email Continue with Email
</Button> </Button>
</Box> </Box>
<Box maxWidth={400}> <Box maxWidth={400}>
<Typography className="tos-p"> <Typography className="tos-p">
By continuing, you agree to our{" "} By continuing, you agree to our{" "}
<Typography <Typography
component="span" component="span"
onClick={() => { onClick={() => {
window.open( window.open(
"https://bluewavelabs.ca/terms-of-service-open-source", "https://bluewavelabs.ca/terms-of-service-open-source",
"_blank", "_blank",
"noreferrer" "noreferrer"
); );
}} }}
sx={{ sx={{
"&:hover": { "&:hover": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
}} }}
> >
Terms of Service Terms of Service
</Typography>{" "} </Typography>{" "}
and{" "} and{" "}
<Typography <Typography
component="span" component="span"
onClick={() => { onClick={() => {
window.open( window.open(
"https://bluewavelabs.ca/privacy-policy-open-source", "https://bluewavelabs.ca/privacy-policy-open-source",
"_blank", "_blank",
"noreferrer" "noreferrer"
); );
}} }}
sx={{ sx={{
"&:hover": { "&:hover": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
}} }}
> >
Privacy Policy. Privacy Policy.
</Typography> </Typography>
</Typography> </Typography>
</Box> </Box>
</Stack> </Stack>
</> </>
); );
}; };
LandingPage.propTypes = { LandingPage.propTypes = {
onContinue: PropTypes.func.isRequired, onContinue: PropTypes.func.isRequired,
}; };
/** /**
@@ -118,79 +118,89 @@ LandingPage.propTypes = {
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => { const StepOne = ({ form, errors, onSubmit, onChange, onBack }) => {
const theme = useTheme(); const theme = useTheme();
const inputRef = useRef(null); const inputRef = useRef(null);
useEffect(() => { useEffect(() => {
if (inputRef.current) { if (inputRef.current) {
inputRef.current.focus(); inputRef.current.focus();
} }
}, []); }, []);
return ( return (
<> <>
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }}
textAlign="center" textAlign="center"
> >
<Box> <Box>
<Typography component="h1">Log In</Typography> <Typography component="h1">Log In</Typography>
<Typography>Enter your email address</Typography> <Typography>Enter your email address</Typography>
</Box> </Box>
<Box textAlign="left" mb={theme.spacing(5)}> <Box
<form noValidate spellCheck={false} onSubmit={onSubmit}> textAlign="left"
<Field mb={theme.spacing(5)}
type="email" >
id="login-email-input" <form
label="Email" noValidate
isRequired={true} spellCheck={false}
placeholder="jordan.ellis@domain.com" onSubmit={onSubmit}
autoComplete="email" >
value={form.email} <Field
onInput={(e) => (e.target.value = e.target.value.toLowerCase())} type="email"
onChange={onChange} id="login-email-input"
error={errors.email} label="Email"
ref={inputRef} isRequired={true}
/> placeholder="jordan.ellis@domain.com"
</form> autoComplete="email"
</Box> value={form.email}
<Stack direction="row" justifyContent="space-between"> onInput={(e) => (e.target.value = e.target.value.toLowerCase())}
<Button onChange={onChange}
variant="outlined" error={errors.email}
color="info" ref={inputRef}
onClick={onBack} />
sx={{ </form>
px: theme.spacing(5), </Box>
"& svg.MuiSvgIcon-root": { <Stack
mr: theme.spacing(3), direction="row"
}, justifyContent="space-between"
}} >
props={{ tabIndex: -1 }} <Button
> variant="outlined"
<ArrowBackRoundedIcon /> color="info"
Back onClick={onBack}
</Button> sx={{
<Button px: theme.spacing(5),
variant="contained" "& svg.MuiSvgIcon-root": {
color="primary" mr: theme.spacing(3),
onClick={onSubmit} },
disabled={errors.email && true} }}
sx={{ width: "30%" }} props={{ tabIndex: -1 }}
> >
Continue <ArrowBackRoundedIcon />
</Button> Back
</Stack> </Button>
</Stack> <Button
</> variant="contained"
); color="primary"
onClick={onSubmit}
disabled={errors.email && true}
sx={{ width: "30%" }}
>
Continue
</Button>
</Stack>
</Stack>
</>
);
}; };
StepOne.propTypes = { StepOne.propTypes = {
form: PropTypes.object.isRequired, form: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired, errors: PropTypes.object.isRequired,
onSubmit: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired,
onBack: PropTypes.func.isRequired, onBack: PropTypes.func.isRequired,
}; };
/** /**
@@ -205,326 +215,333 @@ StepOne.propTypes = {
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => { const StepTwo = ({ form, errors, onSubmit, onChange, onBack }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const inputRef = useRef(null); const inputRef = useRef(null);
useEffect(() => { useEffect(() => {
if (inputRef.current) { if (inputRef.current) {
inputRef.current.focus(); inputRef.current.focus();
} }
}, []); }, []);
const handleNavigate = () => { const handleNavigate = () => {
if (form.email !== "" && !errors.email) { if (form.email !== "" && !errors.email) {
sessionStorage.setItem("email", form.email); sessionStorage.setItem("email", form.email);
} }
navigate("/forgot-password"); navigate("/forgot-password");
}; };
return ( return (
<> <>
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }}
position="relative" position="relative"
textAlign="center" textAlign="center"
> >
<Box> <Box>
<Typography component="h1">Log In</Typography> <Typography component="h1">Log In</Typography>
<Typography>Enter your password</Typography> <Typography>Enter your password</Typography>
</Box> </Box>
<Box textAlign="left" mb={theme.spacing(5)}> <Box
<form noValidate spellCheck={false} onSubmit={onSubmit}> textAlign="left"
<Field mb={theme.spacing(5)}
type="password" >
id="login-password-input" <form
label="Password" noValidate
isRequired={true} spellCheck={false}
placeholder="••••••••••" onSubmit={onSubmit}
autoComplete="current-password" >
value={form.password} <Field
onChange={onChange} type="password"
error={errors.password} id="login-password-input"
ref={inputRef} label="Password"
/> isRequired={true}
</form> placeholder="••••••••••"
</Box> autoComplete="current-password"
<Stack direction="row" justifyContent="space-between"> value={form.password}
<Button onChange={onChange}
variant="outlined" error={errors.password}
color="info" ref={inputRef}
onClick={onBack} />
sx={{ </form>
px: theme.spacing(5), </Box>
"& svg.MuiSvgIcon-root": { <Stack
mr: theme.spacing(3), direction="row"
}, justifyContent="space-between"
}} >
props={{ tabIndex: -1 }} <Button
> variant="outlined"
<ArrowBackRoundedIcon /> color="info"
Back onClick={onBack}
</Button> sx={{
<Button px: theme.spacing(5),
variant="contained" "& svg.MuiSvgIcon-root": {
color="primary" mr: theme.spacing(3),
onClick={onSubmit} },
disabled={errors.password && true} }}
sx={{ width: "30%" }} props={{ tabIndex: -1 }}
> >
Continue <ArrowBackRoundedIcon />
</Button> Back
</Stack> </Button>
<Box <Button
textAlign="center" variant="contained"
sx={{ color="primary"
position: "absolute", onClick={onSubmit}
top: "104%", disabled={errors.password && true}
left: "50%", sx={{ width: "30%" }}
transform: "translateX(-50%)", >
}} Continue
> </Button>
<Typography </Stack>
className="forgot-p" <Box
display="inline-block" textAlign="center"
color={theme.palette.primary.main} sx={{
> position: "absolute",
Forgot password? top: "104%",
</Typography> left: "50%",
<Typography transform: "translateX(-50%)",
component="span" }}
color={theme.palette.primary.main} >
ml={theme.spacing(2)} <Typography
sx={{ userSelect: "none" }} className="forgot-p"
onClick={handleNavigate} display="inline-block"
> color={theme.palette.primary.main}
Reset password >
</Typography> Forgot password?
</Box> </Typography>
</Stack> <Typography
</> component="span"
); color={theme.palette.primary.main}
ml={theme.spacing(2)}
sx={{ userSelect: "none" }}
onClick={handleNavigate}
>
Reset password
</Typography>
</Box>
</Stack>
</>
);
}; };
StepTwo.propTypes = { StepTwo.propTypes = {
form: PropTypes.object.isRequired, form: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired, errors: PropTypes.object.isRequired,
onSubmit: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired,
onBack: PropTypes.func.isRequired, onBack: PropTypes.func.isRequired,
}; };
const Login = () => { const Login = () => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const navigate = useNavigate(); const navigate = useNavigate();
const theme = useTheme(); const theme = useTheme();
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const { authToken } = authState; const { authToken } = authState;
const idMap = { const idMap = {
"login-email-input": "email", "login-email-input": "email",
"login-password-input": "password", "login-password-input": "password",
}; };
const [form, setForm] = useState({ const [form, setForm] = useState({
email: DEMO !== undefined ? "uptimedemo@demo.com" : "", email: DEMO !== undefined ? "uptimedemo@demo.com" : "",
password: DEMO !== undefined ? "Demouser1!" : "", password: DEMO !== undefined ? "Demouser1!" : "",
}); });
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [step, setStep] = useState(0); const [step, setStep] = useState(0);
useEffect(() => { useEffect(() => {
if (authToken) { if (authToken) {
navigate("/monitors"); navigate("/monitors");
return; return;
} }
networkService networkService
.doesSuperAdminExist() .doesSuperAdminExist()
.then((response) => { .then((response) => {
if (response.data.data === false) { if (response.data.data === false) {
navigate("/register"); navigate("/register");
} }
}) })
.catch((error) => { .catch((error) => {
logger.error(error); logger.error(error);
}); });
}, [authToken, navigate]); }, [authToken, navigate]);
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
const name = idMap[id]; const name = idMap[id];
setForm((prev) => ({ setForm((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
const { error } = credentials.validate( const { error } = credentials.validate({ [name]: value }, { abortEarly: false });
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => { setErrors((prev) => {
const prevErrors = { ...prev }; const prevErrors = { ...prev };
if (error) prevErrors[name] = error.details[0].message; if (error) prevErrors[name] = error.details[0].message;
else delete prevErrors[name]; else delete prevErrors[name];
return prevErrors; return prevErrors;
}); });
}; };
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
if (step === 1) { if (step === 1) {
const { error } = credentials.validate( const { error } = credentials.validate(
{ email: form.email }, { email: form.email },
{ abortEarly: false } { abortEarly: false }
); );
if (error) { if (error) {
setErrors((prev) => ({ ...prev, email: error.details[0].message })); setErrors((prev) => ({ ...prev, email: error.details[0].message }));
createToast({ body: error.details[0].message }); createToast({ body: error.details[0].message });
} else { } else {
setStep(2); setStep(2);
} }
} else if (step === 2) { } else if (step === 2) {
const { error } = credentials.validate(form, { abortEarly: false }); const { error } = credentials.validate(form, { abortEarly: false });
if (error) { if (error) {
// validation errors // validation errors
const newErrors = {}; const newErrors = {};
error.details.forEach((err) => { error.details.forEach((err) => {
newErrors[err.path[0]] = err.message; newErrors[err.path[0]] = err.message;
}); });
setErrors(newErrors); setErrors(newErrors);
createToast({ createToast({
body: body:
error.details && error.details.length > 0 error.details && error.details.length > 0
? error.details[0].message ? error.details[0].message
: "Error validating data.", : "Error validating data.",
}); });
} else { } else {
const action = await dispatch(login(form)); const action = await dispatch(login(form));
if (action.payload.success) { if (action.payload.success) {
navigate("/monitors"); navigate("/monitors");
createToast({ createToast({
body: "Welcome back! You're successfully logged in.", body: "Welcome back! You're successfully logged in.",
}); });
} else { } else {
if (action.payload) { if (action.payload) {
if (action.payload.msg === "Incorrect password") if (action.payload.msg === "Incorrect password")
setErrors({ setErrors({
password: password: "The password you provided does not match our records",
"The password you provided does not match our records", });
}); // dispatch errors
// dispatch errors createToast({
createToast({ body: action.payload.msg,
body: action.payload.msg, });
}); } else {
} else { // unknown errors
// unknown errors createToast({
createToast({ body: "Unknown error.",
body: "Unknown error.", });
}); }
} }
} }
} }
} };
};
return ( return (
<Stack <Stack
className="login-page auth" className="login-page auth"
overflow="hidden" overflow="hidden"
sx={{ sx={{
"& h1": { "& h1": {
color: theme.palette.primary.main, color: theme.palette.primary.main,
fontWeight: 600, fontWeight: 600,
fontSize: 28, fontSize: 28,
}, },
"& p": { fontSize: 14, color: theme.palette.text.accent }, "& p": { fontSize: 14, color: theme.palette.text.accent },
"& span": { fontSize: "inherit" }, "& span": { fontSize: "inherit" },
}} }}
> >
<Box <Box
className="background-pattern-svg" className="background-pattern-svg"
sx={{ sx={{
"& svg g g:last-of-type path": { "& svg g g:last-of-type path": {
stroke: theme.palette.border.light, stroke: theme.palette.border.light,
}, },
}} }}
> >
<Background style={{ width: "100%" }} /> <Background style={{ width: "100%" }} />
</Box> </Box>
<Stack <Stack
direction="row" direction="row"
alignItems="center" alignItems="center"
px={theme.spacing(12)} px={theme.spacing(12)}
gap={theme.spacing(4)} gap={theme.spacing(4)}
> >
<Logo style={{ borderRadius: theme.shape.borderRadius }} /> <Logo style={{ borderRadius: theme.shape.borderRadius }} />
<Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography> <Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography>
</Stack> </Stack>
<Stack <Stack
width="100%" width="100%"
maxWidth={600} maxWidth={600}
flex={1} flex={1}
justifyContent="center" justifyContent="center"
px={{ xs: theme.spacing(12), lg: theme.spacing(20) }} px={{ xs: theme.spacing(12), lg: theme.spacing(20) }}
pb={theme.spacing(20)} pb={theme.spacing(20)}
mx="auto" mx="auto"
sx={{ sx={{
"& > .MuiStack-root": { "& > .MuiStack-root": {
border: 1, border: 1,
borderRadius: theme.spacing(5), borderRadius: theme.spacing(5),
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
padding: { padding: {
xs: theme.spacing(12), xs: theme.spacing(12),
sm: theme.spacing(20), sm: theme.spacing(20),
}, },
}, },
}} }}
> >
{step === 0 ? ( {step === 0 ? (
<LandingPage onContinue={() => setStep(1)} /> <LandingPage onContinue={() => setStep(1)} />
) : step === 1 ? ( ) : step === 1 ? (
<StepOne <StepOne
form={form} form={form}
errors={errors} errors={errors}
onSubmit={handleSubmit} onSubmit={handleSubmit}
onChange={handleChange} onChange={handleChange}
onBack={() => setStep(0)} onBack={() => setStep(0)}
/> />
) : ( ) : (
step === 2 && ( step === 2 && (
<StepTwo <StepTwo
form={form} form={form}
errors={errors} errors={errors}
onSubmit={handleSubmit} onSubmit={handleSubmit}
onChange={handleChange} onChange={handleChange}
onBack={() => setStep(1)} onBack={() => setStep(1)}
/> />
) )
)} )}
</Stack> </Stack>
<Box textAlign="center" p={theme.spacing(12)}> <Box
<Typography display="inline-block"> textAlign="center"
Don&apos;t have an account? — p={theme.spacing(12)}
</Typography> >
<Typography <Typography display="inline-block">Don&apos;t have an account? —</Typography>
component="span" <Typography
color={theme.palette.primary.main} component="span"
ml={theme.spacing(2)} color={theme.palette.primary.main}
onClick={() => { ml={theme.spacing(2)}
navigate("/register"); onClick={() => {
}} navigate("/register");
sx={{ userSelect: "none" }} }}
> sx={{ userSelect: "none" }}
Sign Up >
</Typography> Sign Up
</Box> </Typography>
</Stack> </Box>
); </Stack>
);
}; };
export default Login; export default Login;
+105 -103
View File
@@ -11,111 +11,113 @@ import Logo from "../../assets/icons/bwu-icon.svg?react";
import "./index.css"; import "./index.css";
const NewPasswordConfirmed = () => { const NewPasswordConfirmed = () => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const handleNavigate = () => { const handleNavigate = () => {
dispatch(clearAuthState()); dispatch(clearAuthState());
dispatch(clearUptimeMonitorState()); dispatch(clearUptimeMonitorState());
navigate("/login"); navigate("/login");
}; };
return ( return (
<Stack <Stack
className="password-confirmed-page auth" className="password-confirmed-page auth"
overflow="hidden" overflow="hidden"
sx={{ sx={{
"& h1": { "& h1": {
color: theme.palette.primary.main, color: theme.palette.primary.main,
fontWeight: 600, fontWeight: 600,
fontSize: 21, fontSize: 21,
}, },
"& p": { fontSize: 13.5, color: theme.palette.text.accent }, "& p": { fontSize: 13.5, color: theme.palette.text.accent },
}} }}
> >
<Box <Box
className="background-pattern-svg" className="background-pattern-svg"
sx={{ sx={{
"& svg g g:last-of-type path": { "& svg g g:last-of-type path": {
stroke: theme.palette.border.light, stroke: theme.palette.border.light,
}, },
}} }}
> >
<Background style={{ width: "100%" }} /> <Background style={{ width: "100%" }} />
</Box> </Box>
<Stack <Stack
direction="row" direction="row"
alignItems="center" alignItems="center"
px={theme.spacing(12)} px={theme.spacing(12)}
gap={theme.spacing(4)} gap={theme.spacing(4)}
> >
<Logo style={{ borderRadius: theme.shape.borderRadius }} /> <Logo style={{ borderRadius: theme.shape.borderRadius }} />
<Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography> <Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography>
</Stack> </Stack>
<Stack <Stack
width="100%" width="100%"
maxWidth={600} maxWidth={600}
flex={1} flex={1}
justifyContent="center" justifyContent="center"
px={{ xs: theme.spacing(12), lg: theme.spacing(20) }} px={{ xs: theme.spacing(12), lg: theme.spacing(20) }}
pb={theme.spacing(20)} pb={theme.spacing(20)}
mx="auto" mx="auto"
sx={{ sx={{
"& > .MuiStack-root": { "& > .MuiStack-root": {
border: 1, border: 1,
borderRadius: theme.spacing(5), borderRadius: theme.spacing(5),
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
padding: { padding: {
xs: theme.spacing(12), xs: theme.spacing(12),
sm: theme.spacing(20), sm: theme.spacing(20),
}, },
}, },
}} }}
> >
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }}
alignItems="center" alignItems="center"
textAlign="center" textAlign="center"
> >
<Box> <Box>
<IconBox> <IconBox>
<ConfirmIcon alt="password confirm icon" /> <ConfirmIcon alt="password confirm icon" />
</IconBox> </IconBox>
<Typography component="h1">Password reset</Typography> <Typography component="h1">Password reset</Typography>
<Typography mb={theme.spacing(2)}> <Typography mb={theme.spacing(2)}>
Your password has been successfully reset. Click below to log in Your password has been successfully reset. Click below to log in magically.
magically. </Typography>
</Typography> </Box>
</Box> <Button
<Button variant="contained"
variant="contained" color="primary"
color="primary" onClick={() => navigate("/monitors")}
onClick={() => navigate("/monitors")} sx={{
sx={{ width: "100%",
width: "100%", maxWidth: 400,
maxWidth: 400, }}
}} >
> Continue
Continue </Button>
</Button> </Stack>
</Stack> </Stack>
</Stack> <Box
<Box textAlign="center" p={theme.spacing(12)}> textAlign="center"
<Typography display="inline-block">Go back to —</Typography> p={theme.spacing(12)}
<Typography >
component="span" <Typography display="inline-block">Go back to —</Typography>
color={theme.palette.primary.main} <Typography
ml={theme.spacing(2)} component="span"
onClick={handleNavigate} color={theme.palette.primary.main}
sx={{ userSelect: "none" }} ml={theme.spacing(2)}
> onClick={handleNavigate}
Log In sx={{ userSelect: "none" }}
</Typography> >
</Box> Log In
</Stack> </Typography>
); </Box>
</Stack>
);
}; };
export default NewPasswordConfirmed; export default NewPasswordConfirmed;
File diff suppressed because it is too large. Load diff
+274 -274
View File
@@ -17,290 +17,290 @@ import "./index.css";
import { IconBox } from "./styled"; import { IconBox } from "./styled";
const SetNewPassword = () => { const SetNewPassword = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const theme = useTheme(); const theme = useTheme();
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [form, setForm] = useState({ const [form, setForm] = useState({
password: "", password: "",
confirm: "", confirm: "",
}); });
const idMap = { const idMap = {
"register-password-input": "password", "register-password-input": "password",
"confirm-password-input": "confirm", "confirm-password-input": "confirm",
}; };
const { isLoading } = useSelector((state) => state.auth); const { isLoading } = useSelector((state) => state.auth);
const { token } = useParams(); const { token } = useParams();
const handleSubmit = async (e) => { const handleSubmit = async (e) => {
e.preventDefault(); e.preventDefault();
const passwordForm = { ...form }; const passwordForm = { ...form };
const { error } = credentials.validate(passwordForm, { const { error } = credentials.validate(passwordForm, {
abortEarly: false, abortEarly: false,
context: { password: form.password }, context: { password: form.password },
}); });
if (error) { if (error) {
// validation errors // validation errors
const newErrors = {}; const newErrors = {};
error.details.forEach((err) => { error.details.forEach((err) => {
newErrors[err.path[0]] = err.message; newErrors[err.path[0]] = err.message;
}); });
setErrors(newErrors); setErrors(newErrors);
createToast({ createToast({
body: body:
error.details && error.details.length > 0 error.details && error.details.length > 0
? error.details[0].message ? error.details[0].message
: "Error validating data.", : "Error validating data.",
}); });
} else { } else {
delete passwordForm.confirm; delete passwordForm.confirm;
const action = await dispatch( const action = await dispatch(setNewPassword({ token: token, form: passwordForm }));
setNewPassword({ token: token, form: passwordForm }) if (action.payload.success) {
); navigate("/new-password-confirmed");
if (action.payload.success) { createToast({
navigate("/new-password-confirmed"); body: "Your password was reset successfully.",
createToast({ });
body: "Your password was reset successfully.", } else {
}); if (action.payload) {
} else { // dispatch errors
if (action.payload) { createToast({
// dispatch errors body: action.payload.msg,
createToast({ });
body: action.payload.msg, } else {
}); // unknown errors
} else { createToast({
// unknown errors body: "Unknown error.",
createToast({ });
body: "Unknown error.", }
}); }
} }
} };
}
};
const handleChange = (event) => { const handleChange = (event) => {
const { value, id } = event.target; const { value, id } = event.target;
const name = idMap[id]; const name = idMap[id];
setForm((prev) => ({ setForm((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
const { error } = credentials.validate( const { error } = credentials.validate(
{ [name]: value }, { [name]: value },
{ abortEarly: false, context: { password: form.password } } { abortEarly: false, context: { password: form.password } }
); );
setErrors((prev) => { setErrors((prev) => {
const prevErrors = { ...prev }; const prevErrors = { ...prev };
if (error) prevErrors[name] = error.details[0].message; if (error) prevErrors[name] = error.details[0].message;
else delete prevErrors[name]; else delete prevErrors[name];
return prevErrors; return prevErrors;
}); });
}; };
return ( return (
<Stack <Stack
className="set-new-password-page auth" className="set-new-password-page auth"
overflow="hidden" overflow="hidden"
sx={{ sx={{
"& h1": { "& h1": {
color: theme.palette.primary.main, color: theme.palette.primary.main,
fontWeight: 600, fontWeight: 600,
fontSize: 24, fontSize: 24,
}, },
"& p": { "& p": {
fontSize: 14, fontSize: 14,
color: theme.palette.text.accent, color: theme.palette.text.accent,
}, },
}} }}
> >
<Box <Box
className="background-pattern-svg" className="background-pattern-svg"
sx={{ sx={{
"& svg g g:last-of-type path": { "& svg g g:last-of-type path": {
stroke: theme.palette.border.light, stroke: theme.palette.border.light,
}, },
}} }}
> >
<Background style={{ width: "100%" }} /> <Background style={{ width: "100%" }} />
</Box> </Box>
<Stack <Stack
direction="row" direction="row"
alignItems="center" alignItems="center"
px={theme.spacing(12)} px={theme.spacing(12)}
gap={theme.spacing(4)} gap={theme.spacing(4)}
> >
<Logo style={{ borderRadius: theme.shape.borderRadius }} /> <Logo style={{ borderRadius: theme.shape.borderRadius }} />
<Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography> <Typography sx={{ userSelect: "none" }}>BlueWave Uptime</Typography>
</Stack> </Stack>
<Stack <Stack
width="100%" width="100%"
maxWidth={600} maxWidth={600}
flex={1} flex={1}
justifyContent="center" justifyContent="center"
px={{ xs: theme.spacing(12), lg: theme.spacing(20) }} px={{ xs: theme.spacing(12), lg: theme.spacing(20) }}
pb={theme.spacing(12)} pb={theme.spacing(12)}
mx="auto" mx="auto"
sx={{ sx={{
"& > .MuiStack-root": { "& > .MuiStack-root": {
border: 1, border: 1,
borderRadius: theme.spacing(5), borderRadius: theme.spacing(5),
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
padding: { padding: {
xs: theme.spacing(12), xs: theme.spacing(12),
sm: theme.spacing(20), sm: theme.spacing(20),
}, },
}, },
}} }}
> >
<Stack <Stack
gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }} gap={{ xs: theme.spacing(8), sm: theme.spacing(12) }}
alignItems="center" alignItems="center"
textAlign="center" textAlign="center"
> >
<Box> <Box>
<IconBox> <IconBox>
<LockIcon alt="lock icon" /> <LockIcon alt="lock icon" />
</IconBox> </IconBox>
<Typography component="h1">Set new password</Typography> <Typography component="h1">Set new password</Typography>
<Typography> <Typography>
Your new password must be different to previously used passwords. Your new password must be different to previously used passwords.
</Typography> </Typography>
</Box> </Box>
<Box <Box
width="100%" width="100%"
textAlign="left" textAlign="left"
sx={{ sx={{
"& .input-error": { "& .input-error": {
display: "none", display: "none",
}, },
}} }}
> >
<Box <Box
component="form" component="form"
noValidate noValidate
spellCheck={false} spellCheck={false}
onSubmit={handleSubmit} onSubmit={handleSubmit}
> >
<Field <Field
type="password" type="password"
id="register-password-input" id="register-password-input"
label="Password" label="Password"
isRequired={true} isRequired={true}
placeholder="••••••••" placeholder="••••••••"
value={form.password} value={form.password}
onChange={handleChange} onChange={handleChange}
error={errors.password} error={errors.password}
/> />
</Box> </Box>
<Box <Box
component="form" component="form"
noValidate noValidate
spellCheck={false} spellCheck={false}
onSubmit={handleSubmit} onSubmit={handleSubmit}
> >
<Field <Field
type="password" type="password"
id="confirm-password-input" id="confirm-password-input"
label="Confirm password" label="Confirm password"
isRequired={true} isRequired={true}
placeholder="••••••••" placeholder="••••••••"
value={form.confirm} value={form.confirm}
onChange={handleChange} onChange={handleChange}
error={errors.confirm} error={errors.confirm}
/> />
</Box> </Box>
<Stack gap={theme.spacing(4)} mb={theme.spacing(12)}> <Stack
<Check gap={theme.spacing(4)}
text={ mb={theme.spacing(12)}
<> >
<Typography component="span">Must be at least</Typography> 8 <Check
characters long text={
</> <>
} <Typography component="span">Must be at least</Typography> 8
variant={ characters long
errors?.password === "Password is required" </>
? "error" }
: form.password === "" variant={
? "info" errors?.password === "Password is required"
: form.password.length < 8 ? "error"
? "error" : form.password === ""
: "success" ? "info"
} : form.password.length < 8
/> ? "error"
<Check : "success"
text={ }
<> />
<Typography component="span">Must contain</Typography> one <Check
special character and a number text={
</> <>
} <Typography component="span">Must contain</Typography> one special
variant={ character and a number
errors?.password === "Password is required" </>
? "error" }
: form.password === "" variant={
? "info" errors?.password === "Password is required"
: !/^(?=.*[!@#$%^&*(),.?":{}|])(?=.*\d).+$/.test( ? "error"
form.password : form.password === ""
) ? "info"
? "error" : !/^(?=.*[!@#$%^&*(),.?":{}|])(?=.*\d).+$/.test(form.password)
: "success" ? "error"
} : "success"
/> }
<Check />
text={ <Check
<> text={
<Typography component="span"> <>
Must contain at least <Typography component="span">Must contain at least</Typography> one
</Typography>{" "} upper and lower character
one upper and lower character </>
</> }
} variant={
variant={ errors?.password === "Password is required"
errors?.password === "Password is required" ? "error"
? "error" : form.password === ""
: form.password === "" ? "info"
? "info" : !/^(?=.*[A-Z])(?=.*[a-z]).+$/.test(form.password)
: !/^(?=.*[A-Z])(?=.*[a-z]).+$/.test(form.password) ? "error"
? "error" : "success"
: "success" }
} />
/> </Stack>
</Stack> </Box>
</Box> <LoadingButton
<LoadingButton variant="contained"
variant="contained" color="primary"
color="primary" loading={isLoading}
loading={isLoading} onClick={handleSubmit}
onClick={handleSubmit} disabled={Object.keys(errors).length !== 0}
disabled={Object.keys(errors).length !== 0} sx={{ width: "100%", maxWidth: 400 }}
sx={{ width: "100%", maxWidth: 400 }} >
> Reset password
Reset password </LoadingButton>
</LoadingButton> </Stack>
</Stack> </Stack>
</Stack> <Box
<Box textAlign="center" p={theme.spacing(12)}> textAlign="center"
<Typography display="inline-block">Go back to —</Typography> p={theme.spacing(12)}
<Typography >
component="span" <Typography display="inline-block">Go back to —</Typography>
color={theme.palette.primary.main} <Typography
ml={theme.spacing(2)} component="span"
onClick={() => navigate("/login")} color={theme.palette.primary.main}
sx={{ userSelect: "none" }} ml={theme.spacing(2)}
> onClick={() => navigate("/login")}
Log In sx={{ userSelect: "none" }}
</Typography> >
</Box> Log In
</Stack> </Typography>
); </Box>
</Stack>
);
}; };
export default SetNewPassword; export default SetNewPassword;
+73 -73
View File
@@ -1,120 +1,120 @@
/* AUTH */ /* AUTH */
.auth { .auth {
height: 100vh; height: 100vh;
} }
.auth h1 { .auth h1 {
font-size: var(--env-var-font-size-xlarge); font-size: var(--env-var-font-size-xlarge);
font-weight: 600; font-weight: 600;
} }
.auth button:not(.MuiIconButton-root) { .auth button:not(.MuiIconButton-root) {
font-size: var(--env-var-font-size-medium-plus); font-size: var(--env-var-font-size-medium-plus);
} }
.auth p + span { .auth p + span {
opacity: 0.8; opacity: 0.8;
cursor: pointer; cursor: pointer;
transition: opacity 300ms ease-in; transition: opacity 300ms ease-in;
} }
.auth p > span:not(.email-sent-to) { .auth p > span:not(.email-sent-to) {
text-decoration: underline; text-decoration: underline;
text-underline-offset: 2px; text-underline-offset: 2px;
cursor: pointer; cursor: pointer;
transition: all 200ms; transition: all 200ms;
} }
.auth p > span:not(.email-sent-to):hover { .auth p > span:not(.email-sent-to):hover {
text-underline-offset: 4px; text-underline-offset: 4px;
} }
.auth p + span:hover { .auth p + span:hover {
opacity: 1; opacity: 1;
} }
.auth button:not(.MuiIconButton-root) { .auth button:not(.MuiIconButton-root) {
user-select: none; user-select: none;
border-radius: var(--env-var-radius-2); border-radius: var(--env-var-radius-2);
line-height: 1; line-height: 1;
} }
.auth button:not(.MuiIconButton-root), .auth button:not(.MuiIconButton-root),
.auth .field .MuiInputBase-root:has(input) { .auth .field .MuiInputBase-root:has(input) {
height: 38px; height: 38px;
} }
.auth .field svg { .auth .field svg {
width: 24px; width: 24px;
height: 24px; height: 24px;
} }
.auth .field h3.MuiTypography-root, .auth .field h3.MuiTypography-root,
.auth .field .input-error, .auth .field .input-error,
.auth .check span.MuiTypography-root { .auth .check span.MuiTypography-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.auth form + form { .auth form + form {
margin: var(--env-var-spacing-1-plus) 0; margin: var(--env-var-spacing-1-plus) 0;
} }
.auth .email-sent-to { .auth .email-sent-to {
font-weight: 600; font-weight: 600;
cursor: default; cursor: default;
} }
.auth > .MuiStack-root:nth-of-type(2) { .auth > .MuiStack-root:nth-of-type(2) {
height: var(--env-var-nav-bar-height); height: var(--env-var-nav-bar-height);
} }
.auth .background-pattern-svg { .auth .background-pattern-svg {
position: absolute; position: absolute;
top: 0; top: 0;
left: 50%; left: 50%;
transform: translate(-50%, -30%); transform: translate(-50%, -30%);
z-index: -1; z-index: -1;
width: 100%; width: 100%;
max-width: 800px; max-width: 800px;
height: 100%; height: 100%;
max-height: 800px; max-height: 800px;
background-position: center; background-position: center;
background-size: cover; background-size: cover;
background-repeat: no-repeat; background-repeat: no-repeat;
} }
.auth .field { .auth .field {
position: relative; position: relative;
} }
.auth .input-error { .auth .input-error {
position: absolute; position: absolute;
top: calc(100% - 2px); top: calc(100% - 2px);
} }
@media (max-width: 800px) { @media (max-width: 800px) {
.auth h1 { .auth h1 {
font-size: var(--env-var-font-size-large-plus); font-size: var(--env-var-font-size-large-plus);
} }
.auth button:not(.MuiIconButton-root), .auth button:not(.MuiIconButton-root),
.auth .field input, .auth .field input,
.auth p, .auth p,
.auth span { .auth span {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.auth button:not(.MuiIconButton-root), .auth button:not(.MuiIconButton-root),
.auth .field .MuiInputBase-root:has(input) { .auth .field .MuiInputBase-root:has(input) {
height: 36px; height: 36px;
} }
.auth .check span.MuiTypography-root, .auth .check span.MuiTypography-root,
.auth .field .input-error, .auth .field .input-error,
.auth .field h3.MuiTypography-root { .auth .field h3.MuiTypography-root {
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
} }
.auth .check span > span { .auth .check span > span {
display: none; display: none;
} }
.auth form + form { .auth form + form {
margin: var(--env-var-spacing-1-plus) 0; margin: var(--env-var-spacing-1-plus) 0;
} }
.auth .background-pattern-svg { .auth .background-pattern-svg {
max-width: 750px; max-width: 750px;
max-height: 750px; max-height: 750px;
} }
.forgot-password-page h1, .forgot-password-page h1,
.check-email-page h1, .check-email-page h1,
.password-confirmed-page h1, .password-confirmed-page h1,
.set-new-password-page h1 { .set-new-password-page h1 {
font-size: 18px; font-size: 18px;
} }
} }
+22 -22
View File
@@ -1,26 +1,26 @@
import { Box, styled } from "@mui/material"; import { Box, styled } from "@mui/material";
export const IconBox = styled(Box)(({ theme }) => ({ export const IconBox = styled(Box)(({ theme }) => ({
height: 48, height: 48,
minWidth: 48, minWidth: 48,
width: 48, width: 48,
position: "relative", position: "relative",
border: 1, border: 1,
borderStyle: "solid", borderStyle: "solid",
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
borderRadius: 12, borderRadius: 12,
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
margin: "auto", margin: "auto",
marginBottom: 8, marginBottom: 8,
"& svg": { "& svg": {
position: "absolute", position: "absolute",
top: "50%", top: "50%",
left: "50%", left: "50%",
transform: "translate(-50%, -50%)", transform: "translate(-50%, -50%)",
width: 24, width: 24,
height: 24, height: 24,
"& path": { "& path": {
stroke: theme.palette.text.tertiary, stroke: theme.palette.text.tertiary,
}, },
}, },
})); }));
+187 -177
View File
@@ -1,16 +1,16 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import {
TableContainer, TableContainer,
Table, Table,
TableHead, TableHead,
TableRow, TableRow,
TableCell, TableCell,
TableBody, TableBody,
Pagination, Pagination,
PaginationItem, PaginationItem,
Paper, Paper,
Typography, Typography,
Box, Box,
} from "@mui/material"; } from "@mui/material";
import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded"; import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";
@@ -26,183 +26,193 @@ import PlaceholderLight from "../../../assets/Images/data_placeholder.svg?react"
import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?react"; import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?react";
const IncidentTable = ({ monitors, selectedMonitor, filter }) => { const IncidentTable = ({ monitors, selectedMonitor, filter }) => {
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
const theme = useTheme(); const theme = useTheme();
const { authToken, user } = useSelector((state) => state.auth); const { authToken, user } = useSelector((state) => state.auth);
const mode = useSelector((state) => state.ui.mode); const mode = useSelector((state) => state.ui.mode);
const [checks, setChecks] = useState([]); const [checks, setChecks] = useState([]);
const [checksCount, setChecksCount] = useState(0); const [checksCount, setChecksCount] = useState(0);
const [paginationController, setPaginationController] = useState({ const [paginationController, setPaginationController] = useState({
page: 0, page: 0,
rowsPerPage: 14, rowsPerPage: 14,
}); });
useEffect(() => { useEffect(() => {
setPaginationController((prevPaginationController) => ({ setPaginationController((prevPaginationController) => ({
...prevPaginationController, ...prevPaginationController,
page: 0, page: 0,
})); }));
}, [filter, selectedMonitor]); }, [filter, selectedMonitor]);
useEffect(() => { useEffect(() => {
const fetchPage = async () => { const fetchPage = async () => {
if (!monitors || Object.keys(monitors).length === 0) { if (!monitors || Object.keys(monitors).length === 0) {
return; return;
} }
try { try {
let res; let res;
if (selectedMonitor === "0") { if (selectedMonitor === "0") {
res = await networkService.getChecksByTeam({ res = await networkService.getChecksByTeam({
authToken: authToken, authToken: authToken,
teamId: user.teamId, teamId: user.teamId,
sortOrder: "desc", sortOrder: "desc",
limit: null, limit: null,
dateRange: null, dateRange: null,
filter: filter, filter: filter,
page: paginationController.page, page: paginationController.page,
rowsPerPage: paginationController.rowsPerPage, rowsPerPage: paginationController.rowsPerPage,
}); });
} else { } else {
res = await networkService.getChecksByMonitor({ res = await networkService.getChecksByMonitor({
authToken: authToken, authToken: authToken,
monitorId: selectedMonitor, monitorId: selectedMonitor,
sortOrder: "desc", sortOrder: "desc",
limit: null, limit: null,
dateRange: null, dateRange: null,
sitler: filter, sitler: filter,
page: paginationController.page, page: paginationController.page,
rowsPerPage: paginationController.rowsPerPage, rowsPerPage: paginationController.rowsPerPage,
}); });
} }
setChecks(res.data.data.checks); setChecks(res.data.data.checks);
setChecksCount(res.data.data.checksCount); setChecksCount(res.data.data.checksCount);
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
} }
}; };
fetchPage(); fetchPage();
}, [ }, [
authToken, authToken,
user, user,
monitors, monitors,
selectedMonitor, selectedMonitor,
filter, filter,
paginationController.page, paginationController.page,
paginationController.rowsPerPage, paginationController.rowsPerPage,
]); ]);
const handlePageChange = (_, newPage) => { const handlePageChange = (_, newPage) => {
setPaginationController({ setPaginationController({
...paginationController, ...paginationController,
page: newPage - 1, // 0-indexed page: newPage - 1, // 0-indexed
}); });
}; };
let paginationComponent = <></>; let paginationComponent = <></>;
if (checksCount > paginationController.rowsPerPage) { if (checksCount > paginationController.rowsPerPage) {
paginationComponent = ( paginationComponent = (
<Pagination <Pagination
count={Math.ceil(checksCount / paginationController.rowsPerPage)} count={Math.ceil(checksCount / paginationController.rowsPerPage)}
page={paginationController.page + 1} //0-indexed page={paginationController.page + 1} //0-indexed
onChange={handlePageChange} onChange={handlePageChange}
shape="rounded" shape="rounded"
renderItem={(item) => ( renderItem={(item) => (
<PaginationItem <PaginationItem
slots={{ slots={{
previous: ArrowBackRoundedIcon, previous: ArrowBackRoundedIcon,
next: ArrowForwardRoundedIcon, next: ArrowForwardRoundedIcon,
}} }}
{...item} {...item}
/> />
)} )}
sx={{ mt: "auto" }} sx={{ mt: "auto" }}
/> />
); );
} }
let sharedStyles = { let sharedStyles = {
border: 1, border: 1,
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
p: theme.spacing(30), p: theme.spacing(30),
}; };
return ( return (
<> <>
{checks?.length === 0 && selectedMonitor === "0" ? ( {checks?.length === 0 && selectedMonitor === "0" ? (
<Box sx={{ ...sharedStyles }}> <Box sx={{ ...sharedStyles }}>
<Box textAlign="center" pb={theme.spacing(20)}> <Box
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />} textAlign="center"
</Box> pb={theme.spacing(20)}
<Typography textAlign="center" color={theme.palette.text.secondary}> >
No incidents recorded yet. {mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Typography> </Box>
</Box> <Typography
) : checks?.length === 0 ? ( textAlign="center"
<Box sx={{ ...sharedStyles }}> color={theme.palette.text.secondary}
<Box textAlign="center" pb={theme.spacing(20)}> >
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />} No incidents recorded yet.
</Box> </Typography>
<Typography textAlign="center" color={theme.palette.text.secondary}> </Box>
The monitor you have selected has no recorded incidents yet. ) : checks?.length === 0 ? (
</Typography> <Box sx={{ ...sharedStyles }}>
</Box> <Box
) : ( textAlign="center"
<> pb={theme.spacing(20)}
<TableContainer component={Paper}> >
<Table> {mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
<TableHead> </Box>
<TableRow> <Typography
<TableCell>Monitor Name</TableCell> textAlign="center"
<TableCell>Status</TableCell> color={theme.palette.text.secondary}
<TableCell>Date & Time</TableCell> >
<TableCell>Status Code</TableCell> The monitor you have selected has no recorded incidents yet.
<TableCell>Message</TableCell> </Typography>
</TableRow> </Box>
</TableHead> ) : (
<TableBody> <>
{checks.map((check) => { <TableContainer component={Paper}>
const status = check.status === true ? "up" : "down"; <Table>
const formattedDate = formatDateWithTz( <TableHead>
check.createdAt, <TableRow>
"YYYY-MM-DD HH:mm:ss A", <TableCell>Monitor Name</TableCell>
uiTimezone <TableCell>Status</TableCell>
); <TableCell>Date & Time</TableCell>
<TableCell>Status Code</TableCell>
<TableCell>Message</TableCell>
</TableRow>
</TableHead>
<TableBody>
{checks.map((check) => {
const status = check.status === true ? "up" : "down";
const formattedDate = formatDateWithTz(
check.createdAt,
"YYYY-MM-DD HH:mm:ss A",
uiTimezone
);
return ( return (
<TableRow key={check._id}> <TableRow key={check._id}>
<TableCell>{monitors[check.monitorId]?.name}</TableCell> <TableCell>{monitors[check.monitorId]?.name}</TableCell>
<TableCell> <TableCell>
<StatusLabel <StatusLabel
status={status} status={status}
text={status} text={status}
customStyles={{ textTransform: "capitalize" }} customStyles={{ textTransform: "capitalize" }}
/> />
</TableCell> </TableCell>
<TableCell>{formattedDate}</TableCell> <TableCell>{formattedDate}</TableCell>
<TableCell> <TableCell>{check.statusCode ? check.statusCode : "N/A"}</TableCell>
{check.statusCode ? check.statusCode : "N/A"} <TableCell>{check.message}</TableCell>
</TableCell> </TableRow>
<TableCell>{check.message}</TableCell> );
</TableRow> })}
); </TableBody>
})} </Table>
</TableBody> </TableContainer>
</Table> {paginationComponent}
</TableContainer> </>
{paginationComponent} )}
</> </>
)} );
</>
);
}; };
IncidentTable.propTypes = { IncidentTable.propTypes = {
monitors: PropTypes.object.isRequired, monitors: PropTypes.object.isRequired,
selectedMonitor: PropTypes.string.isRequired, selectedMonitor: PropTypes.string.isRequired,
filter: PropTypes.string.isRequired, filter: PropTypes.string.isRequired,
}; };
export default IncidentTable; export default IncidentTable;
+4 -4
View File
@@ -1,11 +1,11 @@
.incidents h1.MuiTypography-root { .incidents h1.MuiTypography-root {
font-size: var(--env-var-font-size-large); font-size: var(--env-var-font-size-large);
font-weight: 600; font-weight: 600;
} }
.incidents button.MuiButtonBase-root, .incidents button.MuiButtonBase-root,
.incidents p.MuiTypography-root { .incidents p.MuiTypography-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.incidents button.MuiButtonBase-root { .incidents button.MuiButtonBase-root {
height: 34px; height: 34px;
} }
+114 -106
View File
@@ -11,119 +11,127 @@ import SkeletonLayout from "./skeleton";
import "./index.css"; import "./index.css";
const Incidents = () => { const Incidents = () => {
const theme = useTheme(); const theme = useTheme();
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const { monitorId } = useParams(); const { monitorId } = useParams();
const [monitors, setMonitors] = useState({}); const [monitors, setMonitors] = useState({});
const [selectedMonitor, setSelectedMonitor] = useState("0"); const [selectedMonitor, setSelectedMonitor] = useState("0");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
// TODO do something with these filters // TODO do something with these filters
const [filter, setFilter] = useState("all"); const [filter, setFilter] = useState("all");
useEffect(() => { useEffect(() => {
const fetchMonitors = async () => { const fetchMonitors = async () => {
setLoading(true); setLoading(true);
const res = await networkService.getMonitorsByTeamId({ const res = await networkService.getMonitorsByTeamId({
authToken: authState.authToken, authToken: authState.authToken,
teamId: authState.user.teamId, teamId: authState.user.teamId,
limit: -1, limit: -1,
types: null, types: null,
status: null, status: null,
checkOrder: null, checkOrder: null,
normalize: null, normalize: null,
page: null, page: null,
rowsPerPage: null, rowsPerPage: null,
filter: null, filter: null,
field: null, field: null,
order: null, order: null,
}); });
// Reduce to a lookup object for 0(1) lookup // Reduce to a lookup object for 0(1) lookup
if (res?.data?.data?.monitors?.length > 0) { if (res?.data?.data?.monitors?.length > 0) {
const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => { const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => {
acc[monitor._id] = monitor; acc[monitor._id] = monitor;
return acc; return acc;
}, {}); }, {});
setMonitors(monitorLookup); setMonitors(monitorLookup);
monitorId !== undefined && setSelectedMonitor(monitorId); monitorId !== undefined && setSelectedMonitor(monitorId);
} }
setLoading(false); setLoading(false);
}; };
fetchMonitors(); fetchMonitors();
}, [authState]); }, [authState]);
useEffect(() => {}, []); useEffect(() => {}, []);
const handleSelect = (event) => { const handleSelect = (event) => {
setSelectedMonitor(event.target.value); setSelectedMonitor(event.target.value);
}; };
return ( return (
<Stack className="incidents table-container" pt={theme.spacing(6)} gap={theme.spacing(12)}> <Stack
{loading ? ( className="incidents table-container"
<SkeletonLayout /> pt={theme.spacing(6)}
) : ( gap={theme.spacing(12)}
<> >
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}> {loading ? (
<Typography <SkeletonLayout />
display="inline-block" ) : (
component="h1" <>
color={theme.palette.text.secondary} <Stack
> direction="row"
Incidents for alignItems="center"
</Typography> gap={theme.spacing(6)}
<Select >
id="incidents-select-monitor" <Typography
placeholder="All servers" display="inline-block"
value={selectedMonitor} component="h1"
onChange={handleSelect} color={theme.palette.text.secondary}
items={Object.values(monitors)} >
sx={{ Incidents for
backgroundColor: theme.palette.background.main, </Typography>
}} <Select
/> id="incidents-select-monitor"
<ButtonGroup placeholder="All servers"
sx={{ value={selectedMonitor}
ml: "auto", onChange={handleSelect}
"& .MuiButtonBase-root, & .MuiButtonBase-root:hover": { items={Object.values(monitors)}
borderColor: theme.palette.border.light, sx={{
}, backgroundColor: theme.palette.background.main,
}} }}
> />
<Button <ButtonGroup
variant="group" sx={{
filled={(filter === "all").toString()} ml: "auto",
onClick={() => setFilter("all")} "& .MuiButtonBase-root, & .MuiButtonBase-root:hover": {
> borderColor: theme.palette.border.light,
All },
</Button> }}
<Button >
variant="group" <Button
filled={(filter === "down").toString()} variant="group"
onClick={() => setFilter("down")} filled={(filter === "all").toString()}
> onClick={() => setFilter("all")}
Down >
</Button> All
<Button </Button>
variant="group" <Button
filled={(filter === "resolve").toString()} variant="group"
onClick={() => setFilter("resolve")} filled={(filter === "down").toString()}
> onClick={() => setFilter("down")}
Cannot Resolve >
</Button> Down
</ButtonGroup> </Button>
</Stack> <Button
<IncidentTable variant="group"
monitors={monitors} filled={(filter === "resolve").toString()}
selectedMonitor={selectedMonitor} onClick={() => setFilter("resolve")}
filter={filter} >
/> Cannot Resolve
</> </Button>
)} </ButtonGroup>
</Stack> </Stack>
); <IncidentTable
monitors={monitors}
selectedMonitor={selectedMonitor}
filter={filter}
/>
</>
)}
</Stack>
);
}; };
export default Incidents; export default Incidents;
+37 -17
View File
@@ -7,24 +7,44 @@ import { useTheme } from "@emotion/react";
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const SkeletonLayout = () => { const SkeletonLayout = () => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<> <>
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}> <Stack
<Skeleton variant="rounded" width={150} height={34} /> direction="row"
<Skeleton variant="rounded" width="15%" height={34} /> alignItems="center"
<Skeleton gap={theme.spacing(6)}
variant="rounded" >
width="20%" <Skeleton
height={34} variant="rounded"
sx={{ ml: "auto" }} width={150}
/> height={34}
</Stack> />
<Skeleton variant="rounded" width="100%" height={300} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={100} /> variant="rounded"
</> width="15%"
); height={34}
/>
<Skeleton
variant="rounded"
width="20%"
height={34}
sx={{ ml: "auto" }}
/>
</Stack>
<Skeleton
variant="rounded"
width="100%"
height={300}
/>
<Skeleton
variant="rounded"
width="100%"
height={100}
/>
</>
);
}; };
export default SkeletonLayout; export default SkeletonLayout;
+4 -4
View File
@@ -1,10 +1,10 @@
.integrations h1.MuiTypography-root { .integrations h1.MuiTypography-root {
font-size: var(--env-var-font-size-large); font-size: var(--env-var-font-size-large);
font-weight: 600; font-weight: 600;
} }
.integrations p.MuiTypography-root { .integrations p.MuiTypography-root {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
} }
.integrations button { .integrations button {
height: var(--env-var-height-2); height: var(--env-var-height-2);
} }
+118 -108
View File
@@ -17,54 +17,61 @@ import "./index.css";
* @returns {JSX.Element} The JSX representation of the IntegrationsComponent. * @returns {JSX.Element} The JSX representation of the IntegrationsComponent.
*/ */
const IntegrationsComponent = ({ icon, header, info, onClick }) => { const IntegrationsComponent = ({ icon, header, info, onClick }) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Grid item lg={6} flexGrow={1}> <Grid
<Stack item
direction="row" lg={6}
justifyContent="space-between" flexGrow={1}
gap={theme.spacing(12)} >
p={theme.spacing(8)} <Stack
pl={theme.spacing(12)} direction="row"
height="100%" justifyContent="space-between"
border={1} gap={theme.spacing(12)}
borderColor={theme.palette.border.light} p={theme.spacing(8)}
borderRadius={theme.shape.borderRadius} pl={theme.spacing(12)}
backgroundColor={theme.palette.background.main} height="100%"
> border={1}
{icon} borderColor={theme.palette.border.light}
<Stack gap={theme.spacing(2)} flex={1}> borderRadius={theme.shape.borderRadius}
<Typography component="h1">{header}</Typography> backgroundColor={theme.palette.background.main}
<Typography >
sx={{ {icon}
maxWidth: "300px", <Stack
wordWrap: "break-word", gap={theme.spacing(2)}
}} flex={1}
> >
{info} <Typography component="h1">{header}</Typography>
</Typography> <Typography
</Stack> sx={{
<Button maxWidth: "300px",
variant="contained" wordWrap: "break-word",
color="primary" }}
onClick={onClick} >
sx={{ alignSelf: "center" }} {info}
disabled={true} </Typography>
> </Stack>
Add <Button
</Button> variant="contained"
</Stack> color="primary"
</Grid> onClick={onClick}
); sx={{ alignSelf: "center" }}
disabled={true}
>
Add
</Button>
</Stack>
</Grid>
);
}; };
// PropTypes for IntegrationsComponent // PropTypes for IntegrationsComponent
IntegrationsComponent.propTypes = { IntegrationsComponent.propTypes = {
icon: PropTypes.object.isRequired, icon: PropTypes.object.isRequired,
header: PropTypes.string.isRequired, header: PropTypes.string.isRequired,
info: PropTypes.string.isRequired, info: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired, onClick: PropTypes.func.isRequired,
}; };
/** /**
@@ -73,73 +80,76 @@ IntegrationsComponent.propTypes = {
*/ */
const Integrations = () => { const Integrations = () => {
const theme = useTheme(); const theme = useTheme();
const integrations = [ const integrations = [
{ {
icon: ( icon: (
<Slack <Slack
alt="slack integration" alt="slack integration"
style={{ width: "45px", height: "45px", alignSelf: "center" }} style={{ width: "45px", height: "45px", alignSelf: "center" }}
/> />
), ),
header: "Slack", header: "Slack",
info: "Connect with Slack and see incidents in a channel", info: "Connect with Slack and see incidents in a channel",
onClick: () => {}, onClick: () => {},
}, },
{ {
icon: ( icon: (
<Discord <Discord
alt="discord integration" alt="discord integration"
style={{ width: "42px", height: "42px", alignSelf: "center" }} style={{ width: "42px", height: "42px", alignSelf: "center" }}
/> />
), ),
header: "Discord", header: "Discord",
info: "Connect with Discord and view incidents directly in a channel", info: "Connect with Discord and view incidents directly in a channel",
onClick: () => {}, onClick: () => {},
}, },
{ {
icon: ( icon: (
<Zapier <Zapier
alt="zapier integration" alt="zapier integration"
style={{ width: "42px", height: "42px", alignSelf: "center" }} style={{ width: "42px", height: "42px", alignSelf: "center" }}
/> />
), ),
header: "Zapier", header: "Zapier",
info: "Send all incidents to Zapier, and then see them everywhere", info: "Send all incidents to Zapier, and then see them everywhere",
onClick: () => {}, onClick: () => {},
}, },
// Add more integrations as needed // Add more integrations as needed
]; ];
return ( return (
<Stack <Stack
className="integrations" className="integrations"
pt={theme.spacing(20)} pt={theme.spacing(20)}
gap={theme.spacing(2)} gap={theme.spacing(2)}
sx={{ sx={{
"& h1, & p": { "& h1, & p": {
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
}, },
}} }}
> >
<Typography component="h1">Integrations</Typography> <Typography component="h1">Integrations</Typography>
<Typography mb={theme.spacing(12)}> <Typography mb={theme.spacing(12)}>
Connect BlueWave Uptime to your favorite service. Connect BlueWave Uptime to your favorite service.
</Typography> </Typography>
<Grid container spacing={theme.spacing(12)}> <Grid
{integrations.map((integration, index) => ( container
<IntegrationsComponent spacing={theme.spacing(12)}
key={index} >
icon={integration.icon} {integrations.map((integration, index) => (
header={integration.header} <IntegrationsComponent
info={integration.info} key={index}
onClick={integration.onClick} icon={integration.icon}
/> header={integration.header}
))} info={integration.info}
</Grid> onClick={integration.onClick}
</Stack> />
); ))}
</Grid>
</Stack>
);
}; };
export default Integrations; export default Integrations;
@@ -1,3 +1,3 @@
.create-maintenance button { .create-maintenance button {
height: 35px; height: 35px;
} }
File diff suppressed because it is too large. Load diff
@@ -1,25 +1,25 @@
import { Stack, styled } from "@mui/material"; import { Stack, styled } from "@mui/material";
export const ConfigBox = styled(Stack)(({ theme }) => ({ export const ConfigBox = styled(Stack)(({ theme }) => ({
border: 1, border: 1,
borderStyle: "solid", borderStyle: "solid",
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: theme.spacing(2), borderRadius: theme.spacing(2),
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
"& > *": { padding: theme.spacing(14) }, "& > *": { padding: theme.spacing(14) },
"& > :first-of-type, & > .MuiStack-root > div:first-of-type": { "& > :first-of-type, & > .MuiStack-root > div:first-of-type": {
flex: 0.6, flex: 0.6,
}, },
"& > div:last-of-type, & > .MuiStack-root > div:last-of-type": { "& > div:last-of-type, & > .MuiStack-root > div:last-of-type": {
flex: 1, flex: 1,
}, },
"& > .MuiStack-root > div:first-of-type": { paddingRight: theme.spacing(14) }, "& > .MuiStack-root > div:first-of-type": { paddingRight: theme.spacing(14) },
"& > .MuiStack-root > div:last-of-type": { "& > .MuiStack-root > div:last-of-type": {
paddingLeft: theme.spacing(14), paddingLeft: theme.spacing(14),
}, },
"& h2": { fontSize: 13.5, fontWeight: 500 }, "& h2": { fontSize: 13.5, fontWeight: 500 },
"& h3, & p": { "& h3, & p": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
"& h3": { fontWeight: 500 }, "& h3": { fontWeight: 500 },
})); }));
@@ -3,13 +3,13 @@ import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { import {
Button, Button,
IconButton, IconButton,
Menu, Menu,
MenuItem, MenuItem,
Modal, Modal,
Stack, Stack,
Typography, Typography,
} from "@mui/material"; } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { logger } from "../../../../Utils/Logger"; import { logger } from "../../../../Utils/Logger";
@@ -19,211 +19,215 @@ import { networkService } from "../../../../main";
import { createToast } from "../../../../Utils/toastUtils"; import { createToast } from "../../../../Utils/toastUtils";
const ActionsMenu = ({ isAdmin, maintenanceWindow, updateCallback }) => { const ActionsMenu = ({ isAdmin, maintenanceWindow, updateCallback }) => {
maintenanceWindow; maintenanceWindow;
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const theme = useTheme(); const theme = useTheme();
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
try { try {
setIsLoading(true); setIsLoading(true);
await networkService.deleteMaintenanceWindow({ await networkService.deleteMaintenanceWindow({
authToken, authToken,
maintenanceWindowId: maintenanceWindow._id, maintenanceWindowId: maintenanceWindow._id,
}); });
updateCallback(); updateCallback();
createToast({ body: "Maintenance window deleted successfully." }); createToast({ body: "Maintenance window deleted successfully." });
} catch (error) { } catch (error) {
createToast({ body: "Failed to delete maintenance window." }); createToast({ body: "Failed to delete maintenance window." });
logger.error("Failed to delete maintenance window", error); logger.error("Failed to delete maintenance window", error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
setIsOpen(false); setIsOpen(false);
}; };
const handlePause = async () => { const handlePause = async () => {
try { try {
setIsLoading(true); setIsLoading(true);
const data = { const data = {
active: !maintenanceWindow.active, active: !maintenanceWindow.active,
}; };
await networkService.editMaintenanceWindow({ await networkService.editMaintenanceWindow({
authToken, authToken,
maintenanceWindowId: maintenanceWindow._id, maintenanceWindowId: maintenanceWindow._id,
maintenanceWindow: data, maintenanceWindow: data,
}); });
updateCallback(); updateCallback();
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
createToast({ body: "Failed to pause maintenance window." }); createToast({ body: "Failed to pause maintenance window." });
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
const handleEdit = () => { const handleEdit = () => {
navigate(`/maintenance/create/${maintenanceWindow._id}`); navigate(`/maintenance/create/${maintenanceWindow._id}`);
}; };
const openMenu = (event) => { const openMenu = (event) => {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
setAnchorEl(event.currentTarget); setAnchorEl(event.currentTarget);
}; };
const openRemove = (e) => { const openRemove = (e) => {
closeMenu(e); closeMenu(e);
setIsOpen(true); setIsOpen(true);
}; };
const closeMenu = (e) => { const closeMenu = (e) => {
e.stopPropagation(); e.stopPropagation();
setAnchorEl(null); setAnchorEl(null);
}; };
const navigate = useNavigate(); const navigate = useNavigate();
return ( return (
<> <>
<IconButton <IconButton
aria-label="monitor actions" aria-label="monitor actions"
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
openMenu(event); openMenu(event);
}} }}
sx={{ sx={{
"&:focus": { "&:focus": {
outline: "none", outline: "none",
}, },
"& svg path": { "& svg path": {
stroke: theme.palette.other.icon, stroke: theme.palette.other.icon,
}, },
}} }}
> >
<Settings /> <Settings />
</IconButton> </IconButton>
<Menu <Menu
className="actions-menu" className="actions-menu"
anchorEl={anchorEl} anchorEl={anchorEl}
open={Boolean(anchorEl)} open={Boolean(anchorEl)}
onClose={(e) => closeMenu(e)} onClose={(e) => closeMenu(e)}
disableScrollLock disableScrollLock
slotProps={{ slotProps={{
paper: { paper: {
sx: { sx: {
"& ul": { p: theme.spacing(2.5) }, "& ul": { p: theme.spacing(2.5) },
"& li": { m: 0 }, "& li": { m: 0 },
"& li:last-of-type": { "& li:last-of-type": {
color: theme.palette.error.text, color: theme.palette.error.text,
}, },
}, },
}, },
}} }}
> >
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
closeMenu(e); closeMenu(e);
e.stopPropagation(); e.stopPropagation();
handleEdit(); handleEdit();
}} }}
> >
Edit Edit
</MenuItem> </MenuItem>
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
handlePause(); handlePause();
closeMenu(e); closeMenu(e);
e.stopPropagation(); e.stopPropagation();
}} }}
> >
{`${maintenanceWindow.active === true ? "Pause" : "Resume"}`} {`${maintenanceWindow.active === true ? "Pause" : "Resume"}`}
</MenuItem> </MenuItem>
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
openRemove(e); openRemove(e);
}} }}
> >
Remove Remove
</MenuItem> </MenuItem>
</Menu> </Menu>
<Modal <Modal
aria-labelledby="modal-delete-monitor" aria-labelledby="modal-delete-monitor"
aria-describedby="delete-monitor-confirmation" aria-describedby="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={(e) => { onClose={(e) => {
e.stopPropagation(); e.stopPropagation();
setIsOpen(false); setIsOpen(false);
}} }}
> >
<Stack <Stack
gap={theme.spacing(2)} gap={theme.spacing(2)}
sx={{ sx={{
position: "absolute", position: "absolute",
top: "50%", top: "50%",
left: "50%", left: "50%",
transform: "translate(-50%, -50%)", transform: "translate(-50%, -50%)",
width: 400, width: 400,
bgcolor: theme.palette.background.main, bgcolor: theme.palette.background.main,
border: 1, border: 1,
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
boxShadow: 24, boxShadow: 24,
p: theme.spacing(15), p: theme.spacing(15),
"&:focus": { "&:focus": {
outline: "none", outline: "none",
}, },
}} }}
> >
<Typography id="modal-delete-maintenance" component="h2" variant="h2"> <Typography
Do you really want to remove this maintenance window? id="modal-delete-maintenance"
</Typography> component="h2"
<Stack variant="h2"
direction="row" >
gap={theme.spacing(4)} Do you really want to remove this maintenance window?
mt={theme.spacing(12)} </Typography>
justifyContent="flex-end" <Stack
> direction="row"
<Button gap={theme.spacing(4)}
variant="text" mt={theme.spacing(12)}
color="info" justifyContent="flex-end"
onClick={(e) => { >
e.stopPropagation(); <Button
setIsOpen(false); variant="text"
}} color="info"
> onClick={(e) => {
Cancel e.stopPropagation();
</Button> setIsOpen(false);
<LoadingButton }}
loading={isLoading} >
variant="contained" Cancel
color="error" </Button>
onClick={(e) => { <LoadingButton
e.stopPropagation(e); loading={isLoading}
handleRemove(e); variant="contained"
}} color="error"
> onClick={(e) => {
Delete e.stopPropagation(e);
</LoadingButton> handleRemove(e);
</Stack> }}
</Stack> >
</Modal> Delete
</> </LoadingButton>
); </Stack>
</Stack>
</Modal>
</>
);
}; };
ActionsMenu.propTypes = { ActionsMenu.propTypes = {
maintenanceWindow: PropTypes.object, maintenanceWindow: PropTypes.object,
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
updateCallback: PropTypes.func, updateCallback: PropTypes.func,
}; };
export default ActionsMenu; export default ActionsMenu;
@@ -1,17 +1,17 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import {
TableContainer, TableContainer,
Table, Table,
TableHead, TableHead,
TableRow, TableRow,
TableCell, TableCell,
TableBody, TableBody,
Paper, Paper,
Box, Box,
TablePagination, TablePagination,
Stack, Stack,
Typography, Typography,
Button, Button,
} from "@mui/material"; } from "@mui/material";
import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded";
import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded"; import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded";
@@ -42,321 +42,321 @@ import dayjs from "dayjs";
* @returns {JSX.Element} Pagination actions component. * @returns {JSX.Element} Pagination actions component.
*/ */
const TablePaginationActions = (props) => { const TablePaginationActions = (props) => {
const { count, page, rowsPerPage, onPageChange } = props; const { count, page, rowsPerPage, onPageChange } = props;
const handleFirstPageButtonClick = (event) => { const handleFirstPageButtonClick = (event) => {
onPageChange(event, 0); onPageChange(event, 0);
}; };
const handleBackButtonClick = (event) => { const handleBackButtonClick = (event) => {
onPageChange(event, page - 1); onPageChange(event, page - 1);
}; };
const handleNextButtonClick = (event) => { const handleNextButtonClick = (event) => {
onPageChange(event, page + 1); onPageChange(event, page + 1);
}; };
const handleLastPageButtonClick = (event) => { const handleLastPageButtonClick = (event) => {
onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
}; };
return ( return (
<Box sx={{ flexShrink: 0, ml: "24px" }}> <Box sx={{ flexShrink: 0, ml: "24px" }}>
<Button <Button
variant="group" variant="group"
onClick={handleFirstPageButtonClick} onClick={handleFirstPageButtonClick}
disabled={page === 0} disabled={page === 0}
aria-label="first page" aria-label="first page"
> >
<LeftArrowDouble /> <LeftArrowDouble />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleBackButtonClick} onClick={handleBackButtonClick}
disabled={page === 0} disabled={page === 0}
aria-label="previous page" aria-label="previous page"
> >
<LeftArrow /> <LeftArrow />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleNextButtonClick} onClick={handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1} disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="next page" aria-label="next page"
> >
<RightArrow /> <RightArrow />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleLastPageButtonClick} onClick={handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1} disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="last page" aria-label="last page"
> >
<RightArrowDouble /> <RightArrowDouble />
</Button> </Button>
</Box> </Box>
); );
}; };
TablePaginationActions.propTypes = { TablePaginationActions.propTypes = {
count: PropTypes.number.isRequired, count: PropTypes.number.isRequired,
page: PropTypes.number.isRequired, page: PropTypes.number.isRequired,
rowsPerPage: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired,
onPageChange: PropTypes.func.isRequired, onPageChange: PropTypes.func.isRequired,
}; };
const MaintenanceTable = ({ const MaintenanceTable = ({
page, page,
setPage, setPage,
sort, sort,
setSort, setSort,
maintenanceWindows, maintenanceWindows,
maintenanceWindowCount, maintenanceWindowCount,
updateCallback, updateCallback,
}) => { }) => {
const { rowsPerPage } = useSelector((state) => state.ui.maintenance); const { rowsPerPage } = useSelector((state) => state.ui.maintenance);
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
const handleChangePage = (event, newPage) => { const handleChangePage = (event, newPage) => {
setPage(newPage); setPage(newPage);
}; };
const getTimeToNextWindow = (startTime, endTime, repeat) => { const getTimeToNextWindow = (startTime, endTime, repeat) => {
//1. Advance time closest to next window as possible //1. Advance time closest to next window as possible
const now = dayjs(); const now = dayjs();
let start = dayjs(startTime); let start = dayjs(startTime);
let end = dayjs(endTime); let end = dayjs(endTime);
if (repeat > 0) { if (repeat > 0) {
// Advance time closest to next window as possible // Advance time closest to next window as possible
while (start.isBefore(now) && end.isBefore(now)) { while (start.isBefore(now) && end.isBefore(now)) {
start = start.add(repeat, "milliseconds"); start = start.add(repeat, "milliseconds");
end = end.add(repeat, "milliseconds"); end = end.add(repeat, "milliseconds");
} }
} }
//Check if we are in a window //Check if we are in a window
if (now.isAfter(start) && now.isBefore(end)) { if (now.isAfter(start) && now.isBefore(end)) {
return "In maintenance window"; return "In maintenance window";
} }
if (start.isAfter(now)) { if (start.isAfter(now)) {
const diffInMinutes = start.diff(now, "minutes"); const diffInMinutes = start.diff(now, "minutes");
const diffInHours = start.diff(now, "hours"); const diffInHours = start.diff(now, "hours");
const diffInDays = start.diff(now, "days"); const diffInDays = start.diff(now, "days");
if (diffInMinutes < 60) { if (diffInMinutes < 60) {
return diffInMinutes + " minutes"; return diffInMinutes + " minutes";
} else if (diffInHours < 24) { } else if (diffInHours < 24) {
return diffInHours + " hours"; return diffInHours + " hours";
} else if (diffInDays < 7) { } else if (diffInDays < 7) {
return diffInDays + " days"; return diffInDays + " days";
} else { } else {
return diffInDays + " days"; return diffInDays + " days";
} }
} }
}; };
const handleChangeRowsPerPage = (event) => { const handleChangeRowsPerPage = (event) => {
dispatch( dispatch(
setRowsPerPage({ setRowsPerPage({
value: parseInt(event.target.value, 10), value: parseInt(event.target.value, 10),
table: "maintenance", table: "maintenance",
}) })
); );
setPage(0); setPage(0);
}; };
/** /**
* Helper function to calculate the range of displayed rows. * Helper function to calculate the range of displayed rows.
* @returns {string} * @returns {string}
*/ */
const getRange = () => { const getRange = () => {
let start = page * rowsPerPage + 1; let start = page * rowsPerPage + 1;
let end = Math.min( let end = Math.min(page * rowsPerPage + rowsPerPage, maintenanceWindowCount);
page * rowsPerPage + rowsPerPage, return `${start} - ${end}`;
maintenanceWindowCount };
);
return `${start} - ${end}`;
};
const handleSort = async (field) => { const handleSort = async (field) => {
let order = ""; let order = "";
if (sort.field !== field) { if (sort.field !== field) {
order = "desc"; order = "desc";
} else { } else {
order = sort.order === "asc" ? "desc" : "asc"; order = sort.order === "asc" ? "desc" : "asc";
} }
setSort({ field, order }); setSort({ field, order });
}; };
return ( return (
<> <>
<TableContainer component={Paper}> <TableContainer component={Paper}>
<Table> <Table>
<TableHead> <TableHead>
<TableRow> <TableRow>
<TableCell <TableCell
sx={{ cursor: "pointer" }} sx={{ cursor: "pointer" }}
onClick={() => handleSort("name")} onClick={() => handleSort("name")}
> >
<Box> <Box>
Maintenance Window Name Maintenance Window Name
<span <span
style={{ style={{
visibility: sort.field === "name" ? "visible" : "hidden", visibility: sort.field === "name" ? "visible" : "hidden",
}} }}
> >
{sort.order === "asc" ? ( {sort.order === "asc" ? (
<ArrowUpwardRoundedIcon /> <ArrowUpwardRoundedIcon />
) : ( ) : (
<ArrowDownwardRoundedIcon /> <ArrowDownwardRoundedIcon />
)} )}
</span> </span>
</Box> </Box>
</TableCell> </TableCell>
<TableCell <TableCell
sx={{ cursor: "pointer" }} sx={{ cursor: "pointer" }}
onClick={() => handleSort("status")} onClick={() => handleSort("status")}
> >
{" "} {" "}
<Box width="max-content"> <Box width="max-content">
{" "} {" "}
Status Status
<span <span
style={{ style={{
visibility: visibility: sort.field === "active" ? "visible" : "hidden",
sort.field === "active" ? "visible" : "hidden", }}
}} >
> {sort.order === "asc" ? (
{sort.order === "asc" ? ( <ArrowUpwardRoundedIcon />
<ArrowUpwardRoundedIcon /> ) : (
) : ( <ArrowDownwardRoundedIcon />
<ArrowDownwardRoundedIcon /> )}
)} </span>
</span> </Box>
</Box> </TableCell>
</TableCell> <TableCell>Next Window</TableCell>
<TableCell>Next Window</TableCell> <TableCell>Repeat</TableCell>
<TableCell>Repeat</TableCell> <TableCell>Actions</TableCell>
<TableCell>Actions</TableCell> </TableRow>
</TableRow> </TableHead>
</TableHead> <TableBody>
<TableBody> {maintenanceWindows.map((maintenanceWindow) => {
{maintenanceWindows.map((maintenanceWindow) => { const text = maintenanceWindow.active ? "active" : "paused";
const text = maintenanceWindow.active ? "active" : "paused"; const status = maintenanceWindow.active ? "up" : "paused";
const status = maintenanceWindow.active ? "up" : "paused"; return (
return ( <TableRow key={maintenanceWindow._id}>
<TableRow key={maintenanceWindow._id}> <TableCell>{maintenanceWindow.name}</TableCell>
<TableCell>{maintenanceWindow.name}</TableCell> <TableCell>
<TableCell> <StatusLabel
<StatusLabel status={status}
status={status} text={text}
text={text} customStyles={{ textTransform: "capitalize" }}
customStyles={{ textTransform: "capitalize" }} />
/> </TableCell>
</TableCell> <TableCell>
<TableCell> {getTimeToNextWindow(
{getTimeToNextWindow( maintenanceWindow.start,
maintenanceWindow.start, maintenanceWindow.end,
maintenanceWindow.end, maintenanceWindow.repeat
maintenanceWindow.repeat )}
)} </TableCell>
</TableCell> <TableCell>
<TableCell> {maintenanceWindow.repeat === 0
{maintenanceWindow.repeat === 0 ? "N/A"
? "N/A" : formatDurationRounded(maintenanceWindow.repeat)}
: formatDurationRounded(maintenanceWindow.repeat)} </TableCell>
</TableCell> <TableCell>
<TableCell> <ActionsMenu
<ActionsMenu maintenanceWindow={maintenanceWindow}
maintenanceWindow={maintenanceWindow} updateCallback={updateCallback}
updateCallback={updateCallback} />
/> </TableCell>
</TableCell> </TableRow>
</TableRow> );
); })}
})} </TableBody>
</TableBody> </Table>
</Table> </TableContainer>
</TableContainer> <Stack
<Stack direction="row"
direction="row" alignItems="center"
alignItems="center" justifyContent="space-between"
justifyContent="space-between" px={theme.spacing(4)}
px={theme.spacing(4)} >
> <Typography
<Typography px={theme.spacing(2)} variant="body2" sx={{ opacity: 0.7 }}> px={theme.spacing(2)}
Showing {getRange()} of {maintenanceWindowCount} maintenance window(s) variant="body2"
</Typography> sx={{ opacity: 0.7 }}
<TablePagination >
component="div" Showing {getRange()} of {maintenanceWindowCount} maintenance window(s)
count={maintenanceWindowCount} </Typography>
page={page} <TablePagination
onPageChange={handleChangePage} component="div"
rowsPerPage={rowsPerPage} count={maintenanceWindowCount}
rowsPerPageOptions={[5, 10, 15, 25]} page={page}
onRowsPerPageChange={handleChangeRowsPerPage} onPageChange={handleChangePage}
ActionsComponent={TablePaginationActions} rowsPerPage={rowsPerPage}
labelRowsPerPage="Rows per page" rowsPerPageOptions={[5, 10, 15, 25]}
labelDisplayedRows={({ page, count }) => onRowsPerPageChange={handleChangeRowsPerPage}
`Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}` ActionsComponent={TablePaginationActions}
} labelRowsPerPage="Rows per page"
slotProps={{ labelDisplayedRows={({ page, count }) =>
select: { `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
MenuProps: { }
keepMounted: true, slotProps={{
disableScrollLock: true, select: {
PaperProps: { MenuProps: {
className: "pagination-dropdown", keepMounted: true,
sx: { disableScrollLock: true,
mt: 0, PaperProps: {
mb: theme.spacing(2), className: "pagination-dropdown",
}, sx: {
}, mt: 0,
transformOrigin: { vertical: "bottom", horizontal: "left" }, mb: theme.spacing(2),
anchorOrigin: { vertical: "top", horizontal: "left" }, },
sx: { mt: theme.spacing(-2) }, },
}, transformOrigin: { vertical: "bottom", horizontal: "left" },
inputProps: { id: "pagination-dropdown" }, anchorOrigin: { vertical: "top", horizontal: "left" },
IconComponent: SelectorVertical, sx: { mt: theme.spacing(-2) },
sx: { },
ml: theme.spacing(4), inputProps: { id: "pagination-dropdown" },
mr: theme.spacing(12), IconComponent: SelectorVertical,
minWidth: theme.spacing(20), sx: {
textAlign: "left", ml: theme.spacing(4),
"&.Mui-focused > div": { mr: theme.spacing(12),
backgroundColor: theme.palette.background.main, 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": { sx={{
stroke: theme.palette.text.tertiary, mt: theme.spacing(6),
strokeWidth: 1.3, color: theme.palette.text.secondary,
}, "& svg path": {
"& .MuiSelect-select": { stroke: theme.palette.text.tertiary,
border: 1, strokeWidth: 1.3,
borderColor: theme.palette.border.light, },
borderRadius: theme.shape.borderRadius, "& .MuiSelect-select": {
}, border: 1,
}} borderColor: theme.palette.border.light,
/> borderRadius: theme.shape.borderRadius,
</Stack> },
</> }}
); />
</Stack>
</>
);
}; };
MaintenanceTable.propTypes = { MaintenanceTable.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
page: PropTypes.number, page: PropTypes.number,
setPage: PropTypes.func, setPage: PropTypes.func,
rowsPerPage: PropTypes.number, rowsPerPage: PropTypes.number,
setRowsPerPage: PropTypes.func, setRowsPerPage: PropTypes.func,
sort: PropTypes.object, sort: PropTypes.object,
setSort: PropTypes.func, setSort: PropTypes.func,
maintenanceWindows: PropTypes.array, maintenanceWindows: PropTypes.array,
maintenanceWindowCount: PropTypes.number, maintenanceWindowCount: PropTypes.number,
updateCallback: PropTypes.func, updateCallback: PropTypes.func,
}; };
const MemoizedMaintenanceTable = memo(MaintenanceTable); const MemoizedMaintenanceTable = memo(MaintenanceTable);
+90 -93
View File
@@ -10,103 +10,100 @@ import Breadcrumbs from "../../Components/Breadcrumbs";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
const Maintenance = ({ isAdmin }) => { const Maintenance = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const { rowsPerPage } = useSelector((state) => state.ui.maintenance); const { rowsPerPage } = useSelector((state) => state.ui.maintenance);
const [maintenanceWindows, setMaintenanceWindows] = useState([]); const [maintenanceWindows, setMaintenanceWindows] = useState([]);
const [maintenanceWindowCount, setMaintenanceWindowCount] = useState(0); const [maintenanceWindowCount, setMaintenanceWindowCount] = useState(0);
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
const [sort, setSort] = useState({}); const [sort, setSort] = useState({});
const [updateTrigger, setUpdateTrigger] = useState(false); const [updateTrigger, setUpdateTrigger] = useState(false);
const handleActionMenuDelete = () => { const handleActionMenuDelete = () => {
setUpdateTrigger((prev) => !prev); setUpdateTrigger((prev) => !prev);
}; };
useEffect(() => { useEffect(() => {
const fetchMaintenanceWindows = async () => { const fetchMaintenanceWindows = async () => {
try { try {
const response = await networkService.getMaintenanceWindowsByTeamId({ const response = await networkService.getMaintenanceWindowsByTeamId({
authToken: authToken, authToken: authToken,
page: page, page: page,
rowsPerPage: rowsPerPage, rowsPerPage: rowsPerPage,
}); });
const { maintenanceWindows, maintenanceWindowCount } = const { maintenanceWindows, maintenanceWindowCount } = response.data.data;
response.data.data; setMaintenanceWindows(maintenanceWindows);
setMaintenanceWindows(maintenanceWindows); setMaintenanceWindowCount(maintenanceWindowCount);
setMaintenanceWindowCount(maintenanceWindowCount); } catch (error) {
} catch (error) { console.log(error);
console.log(error); }
} };
}; fetchMaintenanceWindows();
fetchMaintenanceWindows(); }, [authToken, page, rowsPerPage, updateTrigger]);
}, [authToken, page, rowsPerPage, updateTrigger]);
return ( return (
<Box <Box
className="maintenance table-container" className="maintenance table-container"
sx={{ sx={{
':has(> [class*="fallback__"])': { ':has(> [class*="fallback__"])': {
position: "relative", position: "relative",
border: 1, border: 1,
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
borderStyle: "dashed", borderStyle: "dashed",
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
overflow: "hidden", overflow: "hidden",
}, },
}} }}
> >
{maintenanceWindows.length > 0 && ( {maintenanceWindows.length > 0 && (
<Stack gap={theme.spacing(8)}> <Stack gap={theme.spacing(8)}>
<Stack <Stack
direction="row" direction="row"
justifyContent="space-between" justifyContent="space-between"
alignItems="center" alignItems="center"
mt={theme.spacing(5)} mt={theme.spacing(5)}
> >
<Breadcrumbs <Breadcrumbs list={[{ name: "maintenance", path: "/maintenance" }]} />
list={[{ name: "maintenance", path: "/maintenance" }]} <Button
/> variant="contained"
<Button color="primary"
variant="contained" onClick={() => {
color="primary" navigate("/maintenance/create");
onClick={() => { }}
navigate("/maintenance/create"); sx={{ fontWeight: 500 }}
}} >
sx={{ fontWeight: 500 }} Create maintenance window
> </Button>
Create maintenance window </Stack>
</Button> <MaintenanceTable
</Stack> page={page}
<MaintenanceTable setPage={setPage}
page={page} rowsPerPage={rowsPerPage}
setPage={setPage} sort={sort}
rowsPerPage={rowsPerPage} setSort={setSort}
sort={sort} maintenanceWindows={maintenanceWindows}
setSort={setSort} maintenanceWindowCount={maintenanceWindowCount}
maintenanceWindows={maintenanceWindows} updateCallback={handleActionMenuDelete}
maintenanceWindowCount={maintenanceWindowCount} />
updateCallback={handleActionMenuDelete} </Stack>
/> )}
</Stack> {maintenanceWindows.length === 0 && (
)} <Fallback
{maintenanceWindows.length === 0 && ( title="maintenance window"
<Fallback checks={[
title="maintenance window" "Mark your maintenance periods",
checks={[ "Eliminate any misunderstandings",
"Mark your maintenance periods", "Stop sending alerts in maintenance windows",
"Eliminate any misunderstandings", ]}
"Stop sending alerts in maintenance windows", link="/maintenance/create"
]} isAdmin={true}
link="/maintenance/create" />
isAdmin={true} )}
/> </Box>
)} );
</Box>
);
}; };
export default Maintenance; export default Maintenance;
@@ -1,11 +1,11 @@
.configure-monitor button.MuiButtonBase-root { .configure-monitor button.MuiButtonBase-root {
height: var(--env-var-height-2); height: var(--env-var-height-2);
} }
.configure-monitor .MuiStack-root:has(span.MuiTypography-root.input-error) { .configure-monitor .MuiStack-root:has(span.MuiTypography-root.input-error) {
position: relative; position: relative;
} }
.configure-monitor span.MuiTypography-root.input-error { .configure-monitor span.MuiTypography-root.input-error {
position: absolute; position: absolute;
top: 100%; top: 100%;
} }
+419 -415
View File
@@ -8,11 +8,11 @@ import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { ConfigBox } from "../styled"; import { ConfigBox } from "../styled";
import { import {
updateUptimeMonitor, updateUptimeMonitor,
pauseUptimeMonitor, pauseUptimeMonitor,
getUptimeMonitorById, getUptimeMonitorById,
getUptimeMonitorsByTeamId, getUptimeMonitorsByTeamId,
deleteUptimeMonitor, deleteUptimeMonitor,
} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import Field from "../../../Components/Inputs/Field"; import Field from "../../../Components/Inputs/Field";
import PauseIcon from "../../../assets/icons/pause-icon.svg?react"; import PauseIcon from "../../../assets/icons/pause-icon.svg?react";
@@ -33,11 +33,11 @@ import Dialog from "../../../Components/Dialog";
* @returns {URL} - The parsed URL object if valid, otherwise an empty string. * @returns {URL} - The parsed URL object if valid, otherwise an empty string.
*/ */
const parseUrl = (url) => { const parseUrl = (url) => {
try { try {
return new URL(url); return new URL(url);
} catch (error) { } catch (error) {
return null; return null;
} }
}; };
/** /**
@@ -45,426 +45,430 @@ const parseUrl = (url) => {
* @component * @component
*/ */
const Configure = () => { const Configure = () => {
const MS_PER_MINUTE = 60000; const MS_PER_MINUTE = 60000;
const navigate = useNavigate(); const navigate = useNavigate();
const theme = useTheme(); const theme = useTheme();
const dispatch = useDispatch(); const dispatch = useDispatch();
const { user, authToken } = useSelector((state) => state.auth); const { user, authToken } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.uptimeMonitors); const { isLoading } = useSelector((state) => state.uptimeMonitors);
const [monitor, setMonitor] = useState({}); const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const { monitorId } = useParams(); const { monitorId } = useParams();
const idMap = { const idMap = {
"monitor-url": "url", "monitor-url": "url",
"monitor-name": "name", "monitor-name": "name",
"monitor-checks-http": "type", "monitor-checks-http": "type",
"monitor-checks-ping": "type", "monitor-checks-ping": "type",
"notify-email-default": "notification-email", "notify-email-default": "notification-email",
}; };
useEffect(() => { useEffect(() => {
const fetchMonitor = async () => { const fetchMonitor = async () => {
try { try {
const action = await dispatch( const action = await dispatch(getUptimeMonitorById({ authToken, monitorId }));
getUptimeMonitorById({ authToken, monitorId })
);
if (getUptimeMonitorById.fulfilled.match(action)) { if (getUptimeMonitorById.fulfilled.match(action)) {
const monitor = action.payload.data; const monitor = action.payload.data;
setMonitor(monitor); setMonitor(monitor);
} else if (getUptimeMonitorById.rejected.match(action)) { } else if (getUptimeMonitorById.rejected.match(action)) {
throw new Error(action.error.message); throw new Error(action.error.message);
} }
} catch (error) { } catch (error) {
logger.error("Error fetching monitor of id: " + monitorId); logger.error("Error fetching monitor of id: " + monitorId);
navigate("/not-found", { replace: true }); navigate("/not-found", { replace: true });
} }
}; };
fetchMonitor(); fetchMonitor();
}, [monitorId, authToken, navigate]); }, [monitorId, authToken, navigate]);
const handleChange = (event, name) => { const handleChange = (event, name) => {
let { value, id } = event.target; let { value, id } = event.target;
if (!name) name = idMap[id]; if (!name) name = idMap[id];
if (name.includes("notification-")) { if (name.includes("notification-")) {
name = name.replace("notification-", ""); name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some( let hasNotif = monitor.notifications.some(
(notification) => notification.type === name (notification) => notification.type === name
); );
setMonitor((prev) => { setMonitor((prev) => {
const notifs = [...prev.notifications]; const notifs = [...prev.notifications];
if (hasNotif) { if (hasNotif) {
return { return {
...prev, ...prev,
notifications: notifs.filter((notif) => notif.type !== name), notifications: notifs.filter((notif) => notif.type !== name),
}; };
} else { } else {
return { return {
...prev, ...prev,
notifications: [ notifications: [
...notifs, ...notifs,
name === "email" name === "email"
? { type: name, address: value } ? { type: name, address: value }
: // TODO - phone number : // TODO - phone number
{ type: name, phone: value }, { type: name, phone: value },
], ],
}; };
} }
}); });
} else { } else {
if (name === "interval") { if (name === "interval") {
value = value * MS_PER_MINUTE; value = value * MS_PER_MINUTE;
} }
setMonitor((prev) => ({ setMonitor((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
const validation = monitorValidation.validate( const validation = monitorValidation.validate(
{ [name]: value }, { [name]: value },
{ abortEarly: false } { abortEarly: false }
); );
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (validation.error) if (validation.error) updatedErrors[name] = validation.error.details[0].message;
updatedErrors[name] = validation.error.details[0].message; else delete updatedErrors[name];
else delete updatedErrors[name]; return updatedErrors;
return updatedErrors; });
}); }
} };
};
const handlePause = async () => { const handlePause = async () => {
try { try {
const action = await dispatch( const action = await dispatch(pauseUptimeMonitor({ authToken, monitorId }));
pauseUptimeMonitor({ authToken, monitorId }) if (pauseUptimeMonitor.fulfilled.match(action)) {
); const monitor = action.payload.data;
if (pauseUptimeMonitor.fulfilled.match(action)) { setMonitor(monitor);
const monitor = action.payload.data; } else if (pauseUptimeMonitor.rejected.match(action)) {
setMonitor(monitor); throw new Error(action.error.message);
} else if (pauseUptimeMonitor.rejected.match(action)) { }
throw new Error(action.error.message); } catch (error) {
} logger.error("Error pausing monitor: " + monitorId);
} catch (error) { createToast({ body: "Failed to pause monitor" });
logger.error("Error pausing monitor: " + monitorId); }
createToast({ body: "Failed to pause monitor" }); };
}
};
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const action = await dispatch( const action = await dispatch(updateUptimeMonitor({ authToken, monitor: monitor }));
updateUptimeMonitor({ authToken, monitor: monitor }) if (action.meta.requestStatus === "fulfilled") {
); createToast({ body: "Monitor updated successfully!" });
if (action.meta.requestStatus === "fulfilled") { dispatch(getUptimeMonitorsByTeamId(authToken));
createToast({ body: "Monitor updated successfully!" }); } else {
dispatch(getUptimeMonitorsByTeamId(authToken)); createToast({ body: "Failed to update monitor." });
} else { }
createToast({ body: "Failed to update monitor." }); };
}
};
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
const action = await dispatch(deleteUptimeMonitor({ authToken, monitor })); const action = await dispatch(deleteUptimeMonitor({ authToken, monitor }));
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
navigate("/monitors"); navigate("/monitors");
} else { } else {
createToast({ body: "Failed to delete monitor." }); createToast({ body: "Failed to delete monitor." });
} }
}; };
const frequencies = [ const frequencies = [
{ _id: 1, name: "1 minute" }, { _id: 1, name: "1 minute" },
{ _id: 2, name: "2 minutes" }, { _id: 2, name: "2 minutes" },
{ _id: 3, name: "3 minutes" }, { _id: 3, name: "3 minutes" },
{ _id: 4, name: "4 minutes" }, { _id: 4, name: "4 minutes" },
{ _id: 5, name: "5 minutes" }, { _id: 5, name: "5 minutes" },
]; ];
// Parse the URL // Parse the URL
const parsedUrl = parseUrl(monitor?.url); const parsedUrl = parseUrl(monitor?.url);
const protocol = parsedUrl?.protocol?.replace(":", "") || ""; const protocol = parsedUrl?.protocol?.replace(":", "") || "";
const statusColor = { const statusColor = {
true: theme.palette.success.main, true: theme.palette.success.main,
false: theme.palette.error.main, false: theme.palette.error.main,
undefined: theme.palette.warning.main, undefined: theme.palette.warning.main,
}; };
const statusMsg = { const statusMsg = {
true: "Your site is up.", true: "Your site is up.",
false: "Your site is down.", false: "Your site is down.",
undefined: "Pending...", undefined: "Pending...",
}; };
return ( return (
<Stack className="configure-monitor" gap={theme.spacing(10)}> <Stack
{Object.keys(monitor).length === 0 ? ( className="configure-monitor"
<SkeletonLayout /> gap={theme.spacing(10)}
) : ( >
<> {Object.keys(monitor).length === 0 ? (
<Breadcrumbs <SkeletonLayout />
list={[ ) : (
{ name: "monitors", path: "/monitors" }, <>
{ name: "details", path: `/monitors/${monitorId}` }, <Breadcrumbs
{ name: "configure", path: `/monitors/configure/${monitorId}` }, list={[
]} { name: "monitors", path: "/monitors" },
/> { name: "details", path: `/monitors/${monitorId}` },
<Stack { name: "configure", path: `/monitors/configure/${monitorId}` },
component="form" ]}
noValidate />
spellCheck="false" <Stack
gap={theme.spacing(12)} component="form"
flex={1} noValidate
> spellCheck="false"
<Stack direction="row" gap={theme.spacing(2)}> gap={theme.spacing(12)}
<Box> flex={1}
<Typography component="h1" variant="h1"> >
{monitor.name} <Stack
</Typography> direction="row"
<Stack gap={theme.spacing(2)}
direction="row" >
alignItems="center" <Box>
height="fit-content" <Typography
gap={theme.spacing(2)} component="h1"
> variant="h1"
<Tooltip >
title={statusMsg[monitor?.status ?? undefined]} {monitor.name}
disableInteractive </Typography>
slotProps={{ <Stack
popper: { direction="row"
modifiers: [ alignItems="center"
{ height="fit-content"
name: "offset", gap={theme.spacing(2)}
options: { >
offset: [0, -8], <Tooltip
}, title={statusMsg[monitor?.status ?? undefined]}
}, disableInteractive
], slotProps={{
}, popper: {
}} modifiers: [
> {
<Box> name: "offset",
<PulseDot options: {
color={statusColor[monitor?.status ?? undefined]} offset: [0, -8],
/> },
</Box> },
</Tooltip> ],
<Typography component="h2" variant="h2"> },
{monitor.url?.replace(/^https?:\/\//, "") || "..."} }}
</Typography> >
<Typography <Box>
position="relative" <PulseDot color={statusColor[monitor?.status ?? undefined]} />
variant="body2" </Box>
ml={theme.spacing(6)} </Tooltip>
mt={theme.spacing(1)} <Typography
sx={{ component="h2"
"&:before": { variant="h2"
position: "absolute", >
content: `""`, {monitor.url?.replace(/^https?:\/\//, "") || "..."}
width: 4, </Typography>
height: 4, <Typography
borderRadius: "50%", position="relative"
backgroundColor: theme.palette.text.tertiary, variant="body2"
opacity: 0.8, ml={theme.spacing(6)}
left: -10, mt={theme.spacing(1)}
top: "50%", sx={{
transform: "translateY(-50%)", "&:before": {
}, position: "absolute",
}} content: `""`,
> width: 4,
Editting... height: 4,
</Typography> borderRadius: "50%",
</Stack> backgroundColor: theme.palette.text.tertiary,
</Box> opacity: 0.8,
<Box left: -10,
sx={{ top: "50%",
alignSelf: "flex-end", transform: "translateY(-50%)",
ml: "auto", },
}} }}
> >
<LoadingButton Editting...
variant="contained" </Typography>
color="secondary" </Stack>
loading={isLoading} </Box>
sx={{ <Box
pl: theme.spacing(4), sx={{
pr: theme.spacing(6), alignSelf: "flex-end",
mr: theme.spacing(6), ml: "auto",
"& svg": { }}
mr: theme.spacing(2), >
width: 22, <LoadingButton
height: 22, variant="contained"
"& path": { color="secondary"
stroke: theme.palette.text.tertiary, loading={isLoading}
strokeWidth: 1.7, sx={{
}, pl: theme.spacing(4),
}, pr: theme.spacing(6),
}} mr: theme.spacing(6),
onClick={handlePause} "& svg": {
> mr: theme.spacing(2),
{monitor?.isActive ? ( width: 22,
<> height: 22,
<PauseIcon /> "& path": {
Pause stroke: theme.palette.text.tertiary,
</> strokeWidth: 1.7,
) : ( },
<> },
<ResumeIcon /> }}
Resume onClick={handlePause}
</> >
)} {monitor?.isActive ? (
</LoadingButton> <>
<LoadingButton <PauseIcon />
loading={isLoading} Pause
variant="contained" </>
color="error" ) : (
sx={{ px: theme.spacing(8) }} <>
onClick={() => setIsOpen(true)} <ResumeIcon />
> Resume
Remove </>
</LoadingButton> )}
</Box> </LoadingButton>
</Stack> <LoadingButton
<ConfigBox> loading={isLoading}
<Box> variant="contained"
<Typography component="h2">General settings</Typography> color="error"
<Typography component="p"> sx={{ px: theme.spacing(8) }}
Here you can select the URL of the host, together with the onClick={() => setIsOpen(true)}
type of monitor. >
</Typography> Remove
</Box> </LoadingButton>
<Stack gap={theme.spacing(20)}> </Box>
<Field </Stack>
type={monitor?.type === "http" ? "url" : "text"} <ConfigBox>
https={protocol === "https"} <Box>
id="monitor-url" <Typography component="h2">General settings</Typography>
label="URL to monitor" <Typography component="p">
placeholder="google.com" Here you can select the URL of the host, together with the type of
value={parsedUrl?.host || monitor?.url || ""} monitor.
disabled={true} </Typography>
error={errors["url"]} </Box>
/> <Stack gap={theme.spacing(20)}>
<Field <Field
type="text" type={monitor?.type === "http" ? "url" : "text"}
id="monitor-name" https={protocol === "https"}
label="Display name" id="monitor-url"
isOptional={true} label="URL to monitor"
placeholder="Google" placeholder="google.com"
value={monitor?.name || ""} value={parsedUrl?.host || monitor?.url || ""}
onChange={handleChange} disabled={true}
error={errors["name"]} error={errors["url"]}
/> />
</Stack> <Field
</ConfigBox> type="text"
<ConfigBox> id="monitor-name"
<Box> label="Display name"
<Typography component="h2">Incident notifications</Typography> isOptional={true}
<Typography component="p"> placeholder="Google"
When there is an incident, notify users. value={monitor?.name || ""}
</Typography> onChange={handleChange}
</Box> error={errors["name"]}
<Stack gap={theme.spacing(6)}> />
<Typography component="p"> </Stack>
When there is a new incident, </ConfigBox>
</Typography> <ConfigBox>
<Checkbox <Box>
id="notify-sms" <Typography component="h2">Incident notifications</Typography>
label="Notify via SMS (coming soon)" <Typography component="p">
isChecked={false} When there is an incident, notify users.
value="" </Typography>
onChange={() => logger.warn("disabled")} </Box>
isDisabled={true} <Stack gap={theme.spacing(6)}>
/> <Typography component="p">When there is a new incident,</Typography>
<Checkbox <Checkbox
id="notify-email-default" id="notify-sms"
label={`Notify via email (to ${user.email})`} label="Notify via SMS (coming soon)"
isChecked={ isChecked={false}
monitor?.notifications?.some( value=""
(notification) => notification.type === "email" onChange={() => logger.warn("disabled")}
) || false isDisabled={true}
} />
value={user?.email} <Checkbox
onChange={(event) => handleChange(event)} id="notify-email-default"
/> label={`Notify via email (to ${user.email})`}
<Checkbox isChecked={
id="notify-email" monitor?.notifications?.some(
label="Also notify via email to multiple addresses (coming soon)" (notification) => notification.type === "email"
isChecked={false} ) || false
value="" }
onChange={() => logger.warn("disabled")} value={user?.email}
isDisabled={true} onChange={(event) => handleChange(event)}
/> />
{monitor?.notifications?.some( <Checkbox
(notification) => notification.type === "emails" id="notify-email"
) ? ( label="Also notify via email to multiple addresses (coming soon)"
<Box mx={theme.spacing(16)}> isChecked={false}
<Field value=""
id="notify-email-list" onChange={() => logger.warn("disabled")}
type="text" isDisabled={true}
placeholder="name@gmail.com" />
value="" {monitor?.notifications?.some(
onChange={() => logger.warn("disabled")} (notification) => notification.type === "emails"
/> ) ? (
<Typography mt={theme.spacing(4)}> <Box mx={theme.spacing(16)}>
You can separate multiple emails with a comma <Field
</Typography> id="notify-email-list"
</Box> type="text"
) : ( placeholder="name@gmail.com"
"" value=""
)} onChange={() => logger.warn("disabled")}
</Stack> />
</ConfigBox> <Typography mt={theme.spacing(4)}>
<ConfigBox> You can separate multiple emails with a comma
<Box> </Typography>
<Typography component="h2">Advanced settings</Typography> </Box>
</Box> ) : (
<Stack gap={theme.spacing(20)}> ""
<Select )}
id="monitor-interval-configure" </Stack>
label="Check frequency" </ConfigBox>
value={monitor?.interval / MS_PER_MINUTE || 1} <ConfigBox>
onChange={(event) => handleChange(event, "interval")} <Box>
items={frequencies} <Typography component="h2">Advanced settings</Typography>
/> </Box>
</Stack> <Stack gap={theme.spacing(20)}>
</ConfigBox> <Select
<Stack direction="row" justifyContent="flex-end" mt="auto"> id="monitor-interval-configure"
<LoadingButton label="Check frequency"
variant="contained" value={monitor?.interval / MS_PER_MINUTE || 1}
color="primary" onChange={(event) => handleChange(event, "interval")}
loading={isLoading} items={frequencies}
sx={{ px: theme.spacing(12) }} />
onClick={handleSubmit} </Stack>
> </ConfigBox>
Save <Stack
</LoadingButton> direction="row"
</Stack> justifyContent="flex-end"
</Stack> mt="auto"
</> >
)} <LoadingButton
<Dialog variant="contained"
modelTitle="modal-delete-monitor" color="primary"
modelDescription="delete-monitor-confirmation" loading={isLoading}
open={isOpen} sx={{ px: theme.spacing(12) }}
onClose={() => setIsOpen(false)} onClick={handleSubmit}
title="Do you really want to delete this monitor?" >
confirmationBtnLbl="Delete" Save
confirmationBtnOnClick={handleRemove} </LoadingButton>
cancelBtnLbl="Cancel" </Stack>
cancelBtnOnClick={() => setIsOpen(false)} </Stack>
theme={theme} </>
isLoading={isLoading} )}
description="Once deleted, this monitor cannot be retrieved." <Dialog
> modelTitle="modal-delete-monitor"
</Dialog> modelDescription="delete-monitor-confirmation"
</Stack> open={isOpen}
); onClose={() => setIsOpen(false)}
title="Do you really want to delete this monitor?"
confirmationBtnLbl="Delete"
confirmationBtnOnClick={handleRemove}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(false)}
theme={theme}
isLoading={isLoading}
description="Once deleted, this monitor cannot be retrieved."
></Dialog>
</Stack>
);
}; };
export default Configure; export default Configure;
@@ -7,46 +7,84 @@ import { useTheme } from "@emotion/react";
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const SkeletonLayout = () => { const SkeletonLayout = () => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<> <>
<Skeleton variant="rounded" width="15%" height={34} /> <Skeleton
<Stack gap={theme.spacing(20)} mt={theme.spacing(6)}> variant="rounded"
<Stack direction="row" gap={theme.spacing(4)} mt={theme.spacing(4)}> width="15%"
<Skeleton height={34}
variant="circular" />
style={{ minWidth: 24, minHeight: 24 }} <Stack
/> gap={theme.spacing(20)}
<Box width="80%"> mt={theme.spacing(6)}
<Skeleton >
variant="rounded" <Stack
width="50%" direction="row"
height={24} gap={theme.spacing(4)}
sx={{ mb: theme.spacing(4) }} mt={theme.spacing(4)}
/> >
<Skeleton variant="rounded" width="50%" height={18} /> <Skeleton
</Box> variant="circular"
<Stack style={{ minWidth: 24, minHeight: 24 }}
direction="row" />
gap={theme.spacing(6)} <Box width="80%">
sx={{ <Skeleton
ml: "auto", variant="rounded"
alignSelf: "flex-end", width="50%"
}} height={24}
> sx={{ mb: theme.spacing(4) }}
<Skeleton variant="rounded" width={150} height={34} /> />
</Stack> <Skeleton
</Stack> variant="rounded"
<Skeleton variant="rounded" width="100%" height={200} /> width="50%"
<Skeleton variant="rounded" width="100%" height={200} /> height={18}
<Skeleton variant="rounded" width="100%" height={200} /> />
<Stack direction="row" justifyContent="flex-end"> </Box>
<Skeleton variant="rounded" width="15%" height={34} /> <Stack
</Stack> direction="row"
</Stack> gap={theme.spacing(6)}
</> sx={{
); ml: "auto",
alignSelf: "flex-end",
}}
>
<Skeleton
variant="rounded"
width={150}
height={34}
/>
</Stack>
</Stack>
<Skeleton
variant="rounded"
width="100%"
height={200}
/>
<Skeleton
variant="rounded"
width="100%"
height={200}
/>
<Skeleton
variant="rounded"
width="100%"
height={200}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Skeleton
variant="rounded"
width="15%"
height={34}
/>
</Stack>
</Stack>
</>
);
}; };
export default SkeletonLayout; export default SkeletonLayout;
+343 -339
View File
@@ -26,130 +26,128 @@ const CreateMonitor = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const theme = useTheme(); const theme = useTheme();
const idMap = { const idMap = {
"monitor-url": "url", "monitor-url": "url",
"monitor-name": "name", "monitor-name": "name",
"monitor-checks-http": "type", "monitor-checks-http": "type",
"monitor-checks-ping": "type", "monitor-checks-ping": "type",
"notify-email-default": "notification-email", "notify-email-default": "notification-email",
}; };
const { monitorId } = useParams(); const { monitorId } = useParams();
const [monitor, setMonitor] = useState({ const [monitor, setMonitor] = useState({
url: "", url: "",
name: "", name: "",
type: "http", type: "http",
notifications: [], notifications: [],
interval: 1, interval: 1,
}); });
const [https, setHttps] = useState(true); const [https, setHttps] = useState(true);
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
useEffect(() => { useEffect(() => {
const fetchMonitor = async () => { const fetchMonitor = async () => {
if (monitorId) { if (monitorId) {
const action = await dispatch( const action = await dispatch(getUptimeMonitorById({ authToken, monitorId }));
getUptimeMonitorById({ authToken, monitorId })
);
if (action.payload.success) { if (action.payload.success) {
const data = action.payload.data; const data = action.payload.data;
const { name, ...rest } = data; //data.name is read-only const { name, ...rest } = data; //data.name is read-only
if (rest.type === "http") { if (rest.type === "http") {
const url = new URL(rest.url); const url = new URL(rest.url);
rest.url = url.host; rest.url = url.host;
} }
rest.name = `${name} (Clone)`; rest.name = `${name} (Clone)`;
rest.interval /= MS_PER_MINUTE; rest.interval /= MS_PER_MINUTE;
setMonitor({ setMonitor({
...rest, ...rest,
}); });
} else { } else {
navigate("/not-found", { replace: true }); navigate("/not-found", { replace: true });
createToast({ createToast({
body: "There was an error cloning the monitor.", body: "There was an error cloning the monitor.",
}); });
} }
} }
}; };
fetchMonitor(); fetchMonitor();
}, [monitorId, authToken, monitors]); }, [monitorId, authToken, monitors]);
const handleChange = (event, name) => { const handleChange = (event, name) => {
const { value, id } = event.target; const { value, id } = event.target;
if (!name) name = idMap[id]; if (!name) name = idMap[id];
if (name.includes("notification-")) { if (name.includes("notification-")) {
name = name.replace("notification-", ""); name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some( let hasNotif = monitor.notifications.some(
(notification) => notification.type === name (notification) => notification.type === name
); );
setMonitor((prev) => { setMonitor((prev) => {
const notifs = [...prev.notifications]; const notifs = [...prev.notifications];
if (hasNotif) { if (hasNotif) {
return { return {
...prev, ...prev,
notifications: notifs.filter((notif) => notif.type !== name), notifications: notifs.filter((notif) => notif.type !== name),
}; };
} else { } else {
return { return {
...prev, ...prev,
notifications: [ notifications: [
...notifs, ...notifs,
name === "email" name === "email"
? { type: name, address: value } ? { type: name, address: value }
: // TODO - phone number : // TODO - phone number
{ type: name, phone: value }, { type: name, phone: value },
], ],
}; };
} }
}); });
} else { } else {
setMonitor((prev) => ({ setMonitor((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
const { error } = monitorValidation.validate( const { error } = monitorValidation.validate(
{ [name]: value }, { [name]: value },
{ abortEarly: false } { abortEarly: false }
); );
console.log(error); console.log(error);
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (error) updatedErrors[name] = error.details[0].message; if (error) updatedErrors[name] = error.details[0].message;
else delete updatedErrors[name]; else delete updatedErrors[name];
return updatedErrors; return updatedErrors;
}); });
} }
}; };
const handleCreateMonitor = async (event) => { const handleCreateMonitor = async (event) => {
event.preventDefault(); event.preventDefault();
//obj to submit //obj to submit
let form = { let form = {
url: url:
//preprending protocol for url //preprending protocol for url
monitor.type === "http" monitor.type === "http"
? `http${https ? "s" : ""}://` + monitor.url ? `http${https ? "s" : ""}://` + monitor.url
: monitor.url, : monitor.url,
name: monitor.name === "" ? monitor.url : monitor.name, name: monitor.name === "" ? monitor.url : monitor.name,
type: monitor.type, type: monitor.type,
interval: monitor.interval * MS_PER_MINUTE, interval: monitor.interval * MS_PER_MINUTE,
}; };
const { error } = monitorValidation.validate(form, { const { error } = monitorValidation.validate(form, {
abortEarly: false, abortEarly: false,
}); });
if (error) { if (error) {
const newErrors = {}; const newErrors = {};
error.details.forEach((err) => { error.details.forEach((err) => {
newErrors[err.path[0]] = err.message; newErrors[err.path[0]] = err.message;
}); });
setErrors(newErrors); setErrors(newErrors);
createToast({ body: "Error validation data." }); createToast({ body: "Error validation data." });
} else { } else {
if (monitor.type === "http") { if (monitor.type === "http") {
const checkEndpointAction = await dispatch( const checkEndpointAction = await dispatch(
checkEndpointResolution({ authToken, monitorURL: form.url }) checkEndpointResolution({ authToken, monitorURL: form.url })
@@ -161,228 +159,234 @@ const CreateMonitor = () => {
} }
} }
form = { form = {
...form, ...form,
description: form.name, description: form.name,
teamId: user.teamId, teamId: user.teamId,
userId: user._id, userId: user._id,
notifications: monitor.notifications, notifications: monitor.notifications,
}; };
const action = await dispatch( const action = await dispatch(createUptimeMonitor({ authToken, monitor: form }));
createUptimeMonitor({ authToken, monitor: form }) if (action.meta.requestStatus === "fulfilled") {
); createToast({ body: "Monitor created successfully!" });
if (action.meta.requestStatus === "fulfilled") { navigate("/monitors");
createToast({ body: "Monitor created successfully!" }); } else {
navigate("/monitors"); createToast({ body: "Failed to create monitor." });
} else { }
createToast({ body: "Failed to create monitor." }); }
} };
}
};
//select values //select values
const frequencies = [ const frequencies = [
{ _id: 1, name: "1 minute" }, { _id: 1, name: "1 minute" },
{ _id: 2, name: "2 minutes" }, { _id: 2, name: "2 minutes" },
{ _id: 3, name: "3 minutes" }, { _id: 3, name: "3 minutes" },
{ _id: 4, name: "4 minutes" }, { _id: 4, name: "4 minutes" },
{ _id: 5, name: "5 minutes" }, { _id: 5, name: "5 minutes" },
]; ];
return ( return (
<Box className="create-monitor"> <Box className="create-monitor">
<Breadcrumbs <Breadcrumbs
list={[ list={[
{ name: "monitors", path: "/monitors" }, { name: "monitors", path: "/monitors" },
{ name: "create", path: `/monitors/create` }, { name: "create", path: `/monitors/create` },
]} ]}
/> />
<Stack <Stack
component="form" component="form"
className="create-monitor-form" className="create-monitor-form"
onSubmit={handleCreateMonitor} onSubmit={handleCreateMonitor}
noValidate noValidate
spellCheck="false" spellCheck="false"
gap={theme.spacing(12)} gap={theme.spacing(12)}
mt={theme.spacing(6)} mt={theme.spacing(6)}
> >
<Typography component="h1" variant="h1"> <Typography
<Typography component="span" fontSize="inherit"> component="h1"
Create your{" "} variant="h1"
</Typography> >
<Typography <Typography
component="span" component="span"
variant="h2" fontSize="inherit"
fontSize="inherit" >
fontWeight="inherit" Create your{" "}
> </Typography>
monitor <Typography
</Typography> component="span"
</Typography> variant="h2"
<ConfigBox> fontSize="inherit"
<Box> fontWeight="inherit"
<Typography component="h2">General settings</Typography> >
<Typography component="p"> monitor
Here you can select the URL of the host, together with the type of </Typography>
monitor. </Typography>
</Typography> <ConfigBox>
</Box> <Box>
<Stack gap={theme.spacing(15)}> <Typography component="h2">General settings</Typography>
<Field <Typography component="p">
type={monitor.type === "http" ? "url" : "text"} Here you can select the URL of the host, together with the type of monitor.
id="monitor-url" </Typography>
label="URL to monitor" </Box>
https={https} <Stack gap={theme.spacing(15)}>
placeholder="google.com" <Field
value={monitor.url} type={monitor.type === "http" ? "url" : "text"}
onChange={handleChange} id="monitor-url"
error={errors["url"]} label="URL to monitor"
/> https={https}
<Field placeholder="google.com"
type="text" value={monitor.url}
id="monitor-name" onChange={handleChange}
label="Display name" error={errors["url"]}
isOptional={true} />
placeholder="Google" <Field
value={monitor.name} type="text"
onChange={handleChange} id="monitor-name"
error={errors["name"]} label="Display name"
/> isOptional={true}
</Stack> placeholder="Google"
</ConfigBox> value={monitor.name}
<ConfigBox> onChange={handleChange}
<Box> error={errors["name"]}
<Typography component="h2">Checks to perform</Typography> />
<Typography component="p"> </Stack>
You can always add or remove checks after adding your site. </ConfigBox>
</Typography> <ConfigBox>
</Box> <Box>
<Stack gap={theme.spacing(12)}> <Typography component="h2">Checks to perform</Typography>
<Stack gap={theme.spacing(6)}> <Typography component="p">
<Radio You can always add or remove checks after adding your site.
id="monitor-checks-http" </Typography>
title="Website monitoring" </Box>
desc="Use HTTP(s) to monitor your website or API endpoint." <Stack gap={theme.spacing(12)}>
size="small" <Stack gap={theme.spacing(6)}>
value="http" <Radio
checked={monitor.type === "http"} id="monitor-checks-http"
onChange={(event) => handleChange(event)} title="Website monitoring"
/> desc="Use HTTP(s) to monitor your website or API endpoint."
{monitor.type === "http" ? ( size="small"
<ButtonGroup sx={{ ml: theme.spacing(16) }}> value="http"
<Button checked={monitor.type === "http"}
variant="group" onChange={(event) => handleChange(event)}
filled={https.toString()} />
onClick={() => setHttps(true)} {monitor.type === "http" ? (
> <ButtonGroup sx={{ ml: theme.spacing(16) }}>
HTTPS <Button
</Button> variant="group"
<Button filled={https.toString()}
variant="group" onClick={() => setHttps(true)}
filled={(!https).toString()} >
onClick={() => setHttps(false)} HTTPS
> </Button>
HTTP <Button
</Button> variant="group"
</ButtonGroup> filled={(!https).toString()}
) : ( onClick={() => setHttps(false)}
"" >
)} HTTP
</Stack> </Button>
<Radio </ButtonGroup>
id="monitor-checks-ping" ) : (
title="Ping monitoring" ""
desc="Check whether your server is available or not." )}
size="small" </Stack>
value="ping" <Radio
checked={monitor.type === "ping"} id="monitor-checks-ping"
onChange={(event) => handleChange(event)} title="Ping monitoring"
/> desc="Check whether your server is available or not."
{errors["type"] ? ( size="small"
<Box className="error-container"> value="ping"
<Typography checked={monitor.type === "ping"}
component="p" onChange={(event) => handleChange(event)}
className="input-error" />
color={theme.palette.error.text} {errors["type"] ? (
> <Box className="error-container">
{errors["type"]} <Typography
</Typography> component="p"
</Box> className="input-error"
) : ( color={theme.palette.error.text}
"" >
)} {errors["type"]}
</Stack> </Typography>
</ConfigBox> </Box>
<ConfigBox> ) : (
<Box> ""
<Typography component="h2">Incident notifications</Typography> )}
<Typography component="p"> </Stack>
When there is an incident, notify users. </ConfigBox>
</Typography> <ConfigBox>
</Box> <Box>
<Stack gap={theme.spacing(6)}> <Typography component="h2">Incident notifications</Typography>
<Typography component="p">When there is a new incident,</Typography> <Typography component="p">
<Checkbox When there is an incident, notify users.
id="notify-sms" </Typography>
label="Notify via SMS (coming soon)" </Box>
isChecked={false} <Stack gap={theme.spacing(6)}>
value="" <Typography component="p">When there is a new incident,</Typography>
onChange={() => logger.warn("disabled")} <Checkbox
isDisabled={true} id="notify-sms"
/> label="Notify via SMS (coming soon)"
<Checkbox isChecked={false}
id="notify-email-default" value=""
label={`Notify via email (to ${user.email})`} onChange={() => logger.warn("disabled")}
isChecked={monitor.notifications.some( isDisabled={true}
(notification) => notification.type === "email" />
)} <Checkbox
value={user?.email} id="notify-email-default"
onChange={(event) => handleChange(event)} label={`Notify via email (to ${user.email})`}
/> isChecked={monitor.notifications.some(
<Checkbox (notification) => notification.type === "email"
id="notify-email" )}
label="Also notify via email to multiple addresses (coming soon)" value={user?.email}
isChecked={false} onChange={(event) => handleChange(event)}
value="" />
onChange={() => logger.warn("disabled")} <Checkbox
isDisabled={true} id="notify-email"
/> label="Also notify via email to multiple addresses (coming soon)"
{monitor.notifications.some( isChecked={false}
(notification) => notification.type === "emails" value=""
) ? ( onChange={() => logger.warn("disabled")}
<Box mx={theme.spacing(16)}> isDisabled={true}
<Field />
id="notify-email-list" {monitor.notifications.some(
type="text" (notification) => notification.type === "emails"
placeholder="name@gmail.com" ) ? (
value="" <Box mx={theme.spacing(16)}>
onChange={() => logger.warn("disabled")} <Field
/> id="notify-email-list"
<Typography mt={theme.spacing(4)}> type="text"
You can separate multiple emails with a comma placeholder="name@gmail.com"
</Typography> value=""
</Box> onChange={() => logger.warn("disabled")}
) : ( />
"" <Typography mt={theme.spacing(4)}>
)} You can separate multiple emails with a comma
</Stack> </Typography>
</ConfigBox> </Box>
<ConfigBox> ) : (
<Box> ""
<Typography component="h2">Advanced settings</Typography> )}
</Box> </Stack>
<Stack gap={theme.spacing(12)}> </ConfigBox>
<Select <ConfigBox>
id="monitor-interval" <Box>
label="Check frequency" <Typography component="h2">Advanced settings</Typography>
value={monitor.interval || 1} </Box>
onChange={(event) => handleChange(event, "interval")} <Stack gap={theme.spacing(12)}>
items={frequencies} <Select
/> id="monitor-interval"
</Stack> label="Check frequency"
</ConfigBox> value={monitor.interval || 1}
<Stack direction="row" justifyContent="flex-end"> onChange={(event) => handleChange(event, "interval")}
<LoadingButton items={frequencies}
/>
</Stack>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton
variant="contained" variant="contained"
color="primary" color="primary"
onClick={handleCreateMonitor} onClick={handleCreateMonitor}
@@ -391,10 +395,10 @@ const CreateMonitor = () => {
> >
Create monitor Create monitor
</LoadingButton> </LoadingButton>
</Stack> </Stack>
</Stack> </Stack>
</Box> </Box>
); );
}; };
export default CreateMonitor; export default CreateMonitor;
+295 -267
View File
@@ -1,135 +1,138 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import {
BarChart, BarChart,
Bar, Bar,
XAxis, XAxis,
ResponsiveContainer, ResponsiveContainer,
Cell, Cell,
RadialBarChart, RadialBarChart,
RadialBar, RadialBar,
} from "recharts"; } from "recharts";
import { memo, useMemo, useState } from "react"; import { memo, useMemo, useState } from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { formatDateWithTz } from "../../../../Utils/timeUtils"; import { formatDateWithTz } from "../../../../Utils/timeUtils";
const CustomLabels = ({ const CustomLabels = ({ x, width, height, firstDataPoint, lastDataPoint, type }) => {
x, const uiTimezone = useSelector((state) => state.ui.timezone);
width, const dateFormat = type === "day" ? "MMM D, h:mm A" : "MMM D";
height,
firstDataPoint,
lastDataPoint,
type,
}) => {
const uiTimezone = useSelector((state) => state.ui.timezone);
const dateFormat = type === "day" ? "MMM D, h:mm A" : "MMM D";
return ( return (
<> <>
<text x={x} y={height} dy={-3} textAnchor="start" fontSize={11}> <text
{formatDateWithTz( x={x}
new Date(firstDataPoint.time), y={height}
dateFormat, dy={-3}
uiTimezone textAnchor="start"
)} fontSize={11}
</text> >
<text x={width} y={height} dy={-3} textAnchor="end" fontSize={11}> {formatDateWithTz(new Date(firstDataPoint.time), dateFormat, uiTimezone)}
{formatDateWithTz(new Date(lastDataPoint.time), dateFormat, uiTimezone)} </text>
</text> <text
</> x={width}
); y={height}
dy={-3}
textAnchor="end"
fontSize={11}
>
{formatDateWithTz(new Date(lastDataPoint.time), dateFormat, uiTimezone)}
</text>
</>
);
}; };
CustomLabels.propTypes = { CustomLabels.propTypes = {
x: PropTypes.number.isRequired, x: PropTypes.number.isRequired,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
firstDataPoint: PropTypes.object.isRequired, firstDataPoint: PropTypes.object.isRequired,
lastDataPoint: PropTypes.object.isRequired, lastDataPoint: PropTypes.object.isRequired,
type: PropTypes.string.isRequired, type: PropTypes.string.isRequired,
}; };
const UpBarChart = memo(({ data, type, onBarHover }) => { const UpBarChart = memo(({ data, type, onBarHover }) => {
const theme = useTheme(); const theme = useTheme();
const [chartHovered, setChartHovered] = useState(false); const [chartHovered, setChartHovered] = useState(false);
const [hoveredBarIndex, setHoveredBarIndex] = useState(null); const [hoveredBarIndex, setHoveredBarIndex] = useState(null);
const getColorRange = (uptime) => { const getColorRange = (uptime) => {
return uptime > 80 return uptime > 80
? { main: theme.palette.success.main, light: theme.palette.success.light } ? { main: theme.palette.success.main, light: theme.palette.success.light }
: uptime > 50 : uptime > 50
? { main: theme.palette.warning.main, light: theme.palette.warning.light } ? { main: theme.palette.warning.main, light: theme.palette.warning.light }
: { main: theme.palette.error.text, light: theme.palette.error.light }; : { main: theme.palette.error.text, light: theme.palette.error.light };
}; };
// TODO - REMOVE THIS LATER // TODO - REMOVE THIS LATER
const reversedData = useMemo(() => [...data].reverse(), [data]); const reversedData = useMemo(() => [...data].reverse(), [data]);
return ( return (
<ResponsiveContainer width="100%" minWidth={210} height={155}> <ResponsiveContainer
<BarChart width="100%"
width="100%" minWidth={210}
height="100%" height={155}
data={reversedData} >
onMouseEnter={() => { <BarChart
setChartHovered(true); width="100%"
onBarHover({ time: null, totalChecks: 0, uptimePercentage: 0 }); height="100%"
}} data={reversedData}
onMouseLeave={() => { onMouseEnter={() => {
setChartHovered(false); setChartHovered(true);
setHoveredBarIndex(null); onBarHover({ time: null, totalChecks: 0, uptimePercentage: 0 });
onBarHover(null); }}
}} onMouseLeave={() => {
> setChartHovered(false);
<XAxis setHoveredBarIndex(null);
stroke={theme.palette.border.dark} onBarHover(null);
height={15} }}
tick={false} >
label={ <XAxis
<CustomLabels stroke={theme.palette.border.dark}
x={0} height={15}
y={0} tick={false}
width="100%" label={
height="100%" <CustomLabels
firstDataPoint={reversedData[0]} x={0}
lastDataPoint={reversedData[reversedData.length - 1]} y={0}
type={type} width="100%"
/> height="100%"
} firstDataPoint={reversedData[0]}
/> lastDataPoint={reversedData[reversedData.length - 1]}
<Bar type={type}
dataKey="totalChecks" />
maxBarSize={7} }
background={{ fill: "transparent" }} />
> <Bar
{reversedData.map((entry, index) => { dataKey="totalChecks"
let { main, light } = getColorRange(entry.uptimePercentage); maxBarSize={7}
return ( background={{ fill: "transparent" }}
<Cell >
key={`cell-${entry.time}`} {reversedData.map((entry, index) => {
fill={ let { main, light } = getColorRange(entry.uptimePercentage);
hoveredBarIndex === index ? main : chartHovered ? light : main return (
} <Cell
onMouseEnter={() => { key={`cell-${entry.time}`}
setHoveredBarIndex(index); fill={hoveredBarIndex === index ? main : chartHovered ? light : main}
onBarHover(entry); onMouseEnter={() => {
}} setHoveredBarIndex(index);
onMouseLeave={() => { onBarHover(entry);
setHoveredBarIndex(null); }}
onBarHover({ onMouseLeave={() => {
time: null, setHoveredBarIndex(null);
totalChecks: 0, onBarHover({
uptimePercentage: 0, time: null,
}); totalChecks: 0,
}} uptimePercentage: 0,
/> });
); }}
})} />
</Bar> );
</BarChart> })}
</ResponsiveContainer> </Bar>
); </BarChart>
</ResponsiveContainer>
);
}); });
// Add display name for the component // Add display name for the component
@@ -137,182 +140,207 @@ UpBarChart.displayName = "UpBarChart";
// Validate props using PropTypes // Validate props using PropTypes
UpBarChart.propTypes = { UpBarChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.object), data: PropTypes.arrayOf(PropTypes.object),
type: PropTypes.string, type: PropTypes.string,
onBarHover: PropTypes.func, onBarHover: PropTypes.func,
}; };
export { UpBarChart }; export { UpBarChart };
const DownBarChart = memo(({ data, type, onBarHover }) => { const DownBarChart = memo(({ data, type, onBarHover }) => {
const theme = useTheme(); const theme = useTheme();
const [chartHovered, setChartHovered] = useState(false); const [chartHovered, setChartHovered] = useState(false);
const [hoveredBarIndex, setHoveredBarIndex] = useState(null); const [hoveredBarIndex, setHoveredBarIndex] = useState(null);
// TODO - REMOVE THIS LATER // TODO - REMOVE THIS LATER
const reversedData = useMemo(() => [...data].reverse(), [data]); const reversedData = useMemo(() => [...data].reverse(), [data]);
return ( return (
<ResponsiveContainer width="100%" minWidth={250} height={155}> <ResponsiveContainer
<BarChart width="100%"
width="100%" minWidth={250}
height="100%" height={155}
data={reversedData} >
onMouseEnter={() => { <BarChart
setChartHovered(true); width="100%"
onBarHover({ time: null, totalIncidents: 0 }); height="100%"
}} data={reversedData}
onMouseLeave={() => { onMouseEnter={() => {
setChartHovered(false); setChartHovered(true);
setHoveredBarIndex(null); onBarHover({ time: null, totalIncidents: 0 });
onBarHover(null); }}
}} onMouseLeave={() => {
> setChartHovered(false);
<XAxis setHoveredBarIndex(null);
stroke={theme.palette.border.dark} onBarHover(null);
height={15} }}
tick={false} >
label={ <XAxis
<CustomLabels stroke={theme.palette.border.dark}
x={0} height={15}
y={0} tick={false}
width="100%" label={
height="100%" <CustomLabels
firstDataPoint={reversedData[0]} x={0}
lastDataPoint={reversedData[reversedData.length - 1]} y={0}
type={type} width="100%"
/> height="100%"
} firstDataPoint={reversedData[0]}
/> lastDataPoint={reversedData[reversedData.length - 1]}
<Bar type={type}
dataKey="totalIncidents" />
maxBarSize={7} }
background={{ fill: "transparent" }} />
> <Bar
{reversedData.map((entry, index) => ( dataKey="totalIncidents"
<Cell maxBarSize={7}
key={`cell-${entry.time}`} background={{ fill: "transparent" }}
fill={ >
hoveredBarIndex === index {reversedData.map((entry, index) => (
? theme.palette.error.text <Cell
: chartHovered key={`cell-${entry.time}`}
? theme.palette.error.light fill={
: theme.palette.error.text hoveredBarIndex === index
} ? theme.palette.error.text
onMouseEnter={() => { : chartHovered
setHoveredBarIndex(index); ? theme.palette.error.light
onBarHover(entry); : theme.palette.error.text
}} }
onMouseLeave={() => { onMouseEnter={() => {
setHoveredBarIndex(null); setHoveredBarIndex(index);
onBarHover({ time: null, totalIncidents: 0 }); onBarHover(entry);
}} }}
/> onMouseLeave={() => {
))} setHoveredBarIndex(null);
</Bar> onBarHover({ time: null, totalIncidents: 0 });
</BarChart> }}
</ResponsiveContainer> />
); ))}
</Bar>
</BarChart>
</ResponsiveContainer>
);
}); });
DownBarChart.displayName = "DownBarChart"; DownBarChart.displayName = "DownBarChart";
DownBarChart.propTypes = { DownBarChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.object), data: PropTypes.arrayOf(PropTypes.object),
type: PropTypes.string, type: PropTypes.string,
onBarHover: PropTypes.func, onBarHover: PropTypes.func,
}; };
export { DownBarChart }; export { DownBarChart };
const ResponseGaugeChart = ({ data }) => { const ResponseGaugeChart = ({ data }) => {
const theme = useTheme(); const theme = useTheme();
let max = 1000; // max ms let max = 1000; // max ms
const memoizedData = useMemo( const memoizedData = useMemo(
() => [{ response: max, fill: "transparent", background: false }, ...data], () => [{ response: max, fill: "transparent", background: false }, ...data],
[data[0].response] [data[0].response]
); );
let responseTime = Math.floor(memoizedData[1].response); let responseTime = Math.floor(memoizedData[1].response);
let responseProps = let responseProps =
responseTime <= 200 responseTime <= 200
? { ? {
category: "Excellent", category: "Excellent",
main: theme.palette.success.main, main: theme.palette.success.main,
bg: theme.palette.success.bg, bg: theme.palette.success.bg,
} }
: responseTime <= 500 : responseTime <= 500
? { ? {
category: "Fair", category: "Fair",
main: theme.palette.success.main, main: theme.palette.success.main,
bg: theme.palette.success.bg, bg: theme.palette.success.bg,
} }
: responseTime <= 600 : responseTime <= 600
? { ? {
category: "Acceptable", category: "Acceptable",
main: theme.palette.warning.main, main: theme.palette.warning.main,
bg: theme.palette.warning.bg, bg: theme.palette.warning.bg,
} }
: { : {
category: "Poor", category: "Poor",
main: theme.palette.error.text, main: theme.palette.error.text,
bg: theme.palette.error.bg, bg: theme.palette.error.bg,
}; };
return ( return (
<ResponsiveContainer width="100%" minWidth={210} height={155}> <ResponsiveContainer
<RadialBarChart width="100%"
width="100%" minWidth={210}
height="100%" height={155}
cy="89%" >
data={memoizedData} <RadialBarChart
startAngle={180} width="100%"
endAngle={0} height="100%"
innerRadius={100} cy="89%"
outerRadius={150} data={memoizedData}
> startAngle={180}
<text x={0} y="100%" dx="5%" dy={-2} textAnchor="start" fontSize={11}> endAngle={0}
low innerRadius={100}
</text> outerRadius={150}
<text x="100%" y="100%" dx="-3%" dy={-2} textAnchor="end" fontSize={11}> >
high <text
</text> x={0}
<text y="100%"
x="50%" dx="5%"
y="45%" dy={-2}
textAnchor="middle" textAnchor="start"
dominantBaseline="middle" fontSize={11}
fontSize={18} >
fontWeight={400} low
> </text>
{responseProps.category} <text
</text> x="100%"
<text y="100%"
x="50%" dx="-3%"
y="55%" dy={-2}
textAnchor="middle" textAnchor="end"
dominantBaseline="hanging" fontSize={11}
fontSize={25} >
> high
<tspan fontWeight={600}>{responseTime}</tspan>{" "} </text>
<tspan opacity={0.8}>ms</tspan> <text
</text> x="50%"
<RadialBar y="45%"
background={{ fill: responseProps.bg }} textAnchor="middle"
clockWise dominantBaseline="middle"
dataKey="response" fontSize={18}
stroke="none" fontWeight={400}
> >
<Cell fill="transparent" background={false} barSize={0} /> {responseProps.category}
<Cell fill={responseProps.main} /> </text>
</RadialBar> <text
</RadialBarChart> x="50%"
</ResponsiveContainer> y="55%"
); textAnchor="middle"
dominantBaseline="hanging"
fontSize={25}
>
<tspan fontWeight={600}>{responseTime}</tspan> <tspan opacity={0.8}>ms</tspan>
</text>
<RadialBar
background={{ fill: responseProps.bg }}
clockWise
dataKey="response"
stroke="none"
>
<Cell
fill="transparent"
background={false}
barSize={0}
/>
<Cell fill={responseProps.main} />
</RadialBar>
</RadialBarChart>
</ResponsiveContainer>
);
}; };
ResponseGaugeChart.propTypes = { ResponseGaugeChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.object).isRequired, data: PropTypes.arrayOf(PropTypes.object).isRequired,
}; };
export { ResponseGaugeChart }; export { ResponseGaugeChart };
@@ -1,14 +1,14 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import {
TableContainer, TableContainer,
Table, Table,
TableHead, TableHead,
TableRow, TableRow,
TableCell, TableCell,
TableBody, TableBody,
PaginationItem, PaginationItem,
Pagination, Pagination,
Paper, Paper,
} from "@mui/material"; } from "@mui/material";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
@@ -21,128 +21,126 @@ import { logger } from "../../../../Utils/Logger";
import { formatDateWithTz } from "../../../../Utils/timeUtils"; import { formatDateWithTz } from "../../../../Utils/timeUtils";
const PaginationTable = ({ monitorId, dateRange }) => { const PaginationTable = ({ monitorId, dateRange }) => {
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const [checks, setChecks] = useState([]); const [checks, setChecks] = useState([]);
const [checksCount, setChecksCount] = useState(0); const [checksCount, setChecksCount] = useState(0);
const [paginationController, setPaginationController] = useState({ const [paginationController, setPaginationController] = useState({
page: 0, page: 0,
rowsPerPage: 5, rowsPerPage: 5,
}); });
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
useEffect(() => { useEffect(() => {
setPaginationController((prevPaginationController) => ({ setPaginationController((prevPaginationController) => ({
...prevPaginationController, ...prevPaginationController,
page: 0, page: 0,
})); }));
}, [dateRange]); }, [dateRange]);
useEffect(() => { useEffect(() => {
const fetchPage = async () => { const fetchPage = async () => {
try { try {
const res = await networkService.getChecksByMonitor({ const res = await networkService.getChecksByMonitor({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
sortOrder: "desc", sortOrder: "desc",
limit: null, limit: null,
dateRange: dateRange, dateRange: dateRange,
filter: null, filter: null,
page: paginationController.page, page: paginationController.page,
rowsPerPage: paginationController.rowsPerPage, rowsPerPage: paginationController.rowsPerPage,
}); });
setChecks(res.data.data.checks); setChecks(res.data.data.checks);
setChecksCount(res.data.data.checksCount); setChecksCount(res.data.data.checksCount);
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
} }
}; };
fetchPage(); fetchPage();
}, [ }, [
authToken, authToken,
monitorId, monitorId,
dateRange, dateRange,
paginationController.page, paginationController.page,
paginationController.rowsPerPage, paginationController.rowsPerPage,
]); ]);
const handlePageChange = (_, newPage) => { const handlePageChange = (_, newPage) => {
setPaginationController({ setPaginationController({
...paginationController, ...paginationController,
page: newPage - 1, // 0-indexed page: newPage - 1, // 0-indexed
}); });
}; };
let paginationComponent = <></>; let paginationComponent = <></>;
if (checksCount > paginationController.rowsPerPage) { if (checksCount > paginationController.rowsPerPage) {
paginationComponent = ( paginationComponent = (
<Pagination <Pagination
count={Math.ceil(checksCount / paginationController.rowsPerPage)} count={Math.ceil(checksCount / paginationController.rowsPerPage)}
page={paginationController.page + 1} //0-indexed page={paginationController.page + 1} //0-indexed
onChange={handlePageChange} onChange={handlePageChange}
shape="rounded" shape="rounded"
renderItem={(item) => ( renderItem={(item) => (
<PaginationItem <PaginationItem
slots={{ slots={{
previous: ArrowBackRoundedIcon, previous: ArrowBackRoundedIcon,
next: ArrowForwardRoundedIcon, next: ArrowForwardRoundedIcon,
}} }}
{...item} {...item}
/> />
)} )}
/> />
); );
} }
return ( return (
<> <>
<TableContainer component={Paper}> <TableContainer component={Paper}>
<Table> <Table>
<TableHead> <TableHead>
<TableRow> <TableRow>
<TableCell>Status</TableCell> <TableCell>Status</TableCell>
<TableCell>Date & Time</TableCell> <TableCell>Date & Time</TableCell>
<TableCell>Status Code</TableCell> <TableCell>Status Code</TableCell>
<TableCell>Message</TableCell> <TableCell>Message</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
<TableBody> <TableBody>
{checks.map((check) => { {checks.map((check) => {
const status = check.status === true ? "up" : "down"; const status = check.status === true ? "up" : "down";
return ( return (
<TableRow key={check._id}> <TableRow key={check._id}>
<TableCell> <TableCell>
<StatusLabel <StatusLabel
status={status} status={status}
text={status} text={status}
customStyles={{ textTransform: "capitalize" }} customStyles={{ textTransform: "capitalize" }}
/> />
</TableCell> </TableCell>
<TableCell> <TableCell>
{formatDateWithTz( {formatDateWithTz(
check.createdAt, check.createdAt,
"ddd, MMMM D, YYYY, HH:mm A", "ddd, MMMM D, YYYY, HH:mm A",
uiTimezone uiTimezone
)} )}
</TableCell> </TableCell>
<TableCell> <TableCell>{check.statusCode ? check.statusCode : "N/A"}</TableCell>
{check.statusCode ? check.statusCode : "N/A"} <TableCell>{check.message}</TableCell>
</TableCell> </TableRow>
<TableCell>{check.message}</TableCell> );
</TableRow> })}
); </TableBody>
})} </Table>
</TableBody> </TableContainer>
</Table> {paginationComponent}
</TableContainer> </>
{paginationComponent} );
</>
);
}; };
PaginationTable.propTypes = { PaginationTable.propTypes = {
monitorId: PropTypes.string.isRequired, monitorId: PropTypes.string.isRequired,
dateRange: PropTypes.string.isRequired, dateRange: PropTypes.string.isRequired,
}; };
export default PaginationTable; export default PaginationTable;
@@ -1 +0,0 @@
+108 -61
View File
@@ -6,68 +6,115 @@ import { Box, Skeleton, Stack, useTheme } from "@mui/material";
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const SkeletonLayout = () => { const SkeletonLayout = () => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<> <>
<Skeleton variant="rounded" width="20%" height={34} /> <Skeleton
<Stack gap={theme.spacing(20)} mt={theme.spacing(6)}> variant="rounded"
<Stack direction="row" gap={theme.spacing(4)} mt={theme.spacing(4)}> width="20%"
<Skeleton height={34}
variant="circular" />
style={{ minWidth: 24, minHeight: 24 }} <Stack
/> gap={theme.spacing(20)}
<Box width="80%"> mt={theme.spacing(6)}
<Skeleton variant="rounded" width="50%" height={24} /> >
<Skeleton <Stack
variant="rounded" direction="row"
width="50%" gap={theme.spacing(4)}
height={18} mt={theme.spacing(4)}
sx={{ mt: theme.spacing(4) }} >
/> <Skeleton
</Box> variant="circular"
<Skeleton style={{ minWidth: 24, minHeight: 24 }}
variant="rounded" />
width="20%" <Box width="80%">
height={34} <Skeleton
sx={{ alignSelf: "flex-end" }} variant="rounded"
/> width="50%"
</Stack> height={24}
<Stack />
direction="row" <Skeleton
justifyContent="space-between" variant="rounded"
gap={theme.spacing(12)} width="50%"
> height={18}
<Skeleton variant="rounded" width="100%" height={80} /> sx={{ mt: theme.spacing(4) }}
<Skeleton variant="rounded" width="100%" height={80} /> />
<Skeleton variant="rounded" width="100%" height={80} /> </Box>
</Stack> <Skeleton
<Box> variant="rounded"
<Stack width="20%"
direction="row" height={34}
justifyContent="space-between" sx={{ alignSelf: "flex-end" }}
mb={theme.spacing(8)} />
> </Stack>
<Skeleton <Stack
variant="rounded" direction="row"
width="20%" justifyContent="space-between"
height={24} gap={theme.spacing(12)}
sx={{ alignSelf: "flex-end" }} >
/> <Skeleton
<Skeleton variant="rounded" width="20%" height={34} /> variant="rounded"
</Stack> width="100%"
<Box sx={{ height: "200px" }}> height={80}
<Skeleton variant="rounded" width="100%" height="100%" /> />
</Box> <Skeleton
</Box> variant="rounded"
<Stack gap={theme.spacing(8)}> width="100%"
<Skeleton variant="rounded" width="20%" height={24} /> height={80}
<Skeleton variant="rounded" width="100%" height={200} /> />
<Skeleton variant="rounded" width="100%" height={50} /> <Skeleton
</Stack> variant="rounded"
</Stack> width="100%"
</> height={80}
); />
</Stack>
<Box>
<Stack
direction="row"
justifyContent="space-between"
mb={theme.spacing(8)}
>
<Skeleton
variant="rounded"
width="20%"
height={24}
sx={{ alignSelf: "flex-end" }}
/>
<Skeleton
variant="rounded"
width="20%"
height={34}
/>
</Stack>
<Box sx={{ height: "200px" }}>
<Skeleton
variant="rounded"
width="100%"
height="100%"
/>
</Box>
</Box>
<Stack gap={theme.spacing(8)}>
<Skeleton
variant="rounded"
width="20%"
height={24}
/>
<Skeleton
variant="rounded"
width="100%"
height={200}
/>
<Skeleton
variant="rounded"
width="100%"
height={50}
/>
</Stack>
</Stack>
</>
);
}; };
export default SkeletonLayout; export default SkeletonLayout;
+86 -86
View File
@@ -1,96 +1,96 @@
import { Box, Stack, styled } from "@mui/material"; import { Box, Stack, styled } from "@mui/material";
export const ChartBox = styled(Stack)(({ theme }) => ({ export const ChartBox = styled(Stack)(({ theme }) => ({
flex: "1 30%", flex: "1 30%",
gap: theme.spacing(8), gap: theme.spacing(8),
height: 300, height: 300,
minWidth: 250, minWidth: 250,
padding: theme.spacing(8), padding: theme.spacing(8),
border: 1, border: 1,
borderStyle: "solid", borderStyle: "solid",
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: 4, borderRadius: 4,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
"& h2": { "& h2": {
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
fontSize: 15, fontSize: 15,
fontWeight: 500, fontWeight: 500,
}, },
"& .MuiBox-root:not(.area-tooltip) p": { "& .MuiBox-root:not(.area-tooltip) p": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
fontSize: 13, fontSize: 13,
}, },
"& .MuiBox-root > span": { "& .MuiBox-root > span": {
color: theme.palette.text.primary, color: theme.palette.text.primary,
fontSize: 20, fontSize: 20,
"& span": { "& span": {
opacity: 0.8, opacity: 0.8,
marginLeft: 2, marginLeft: 2,
fontSize: 15, fontSize: 15,
}, },
}, },
"& .MuiStack-root": { "& .MuiStack-root": {
flexDirection: "row", flexDirection: "row",
gap: theme.spacing(6), gap: theme.spacing(6),
}, },
"& .MuiStack-root:first-of-type": { "& .MuiStack-root:first-of-type": {
alignItems: "center", alignItems: "center",
}, },
"& tspan, & text": { "& tspan, & text": {
fill: theme.palette.text.tertiary, fill: theme.palette.text.tertiary,
}, },
"& path": { "& path": {
transition: "fill 300ms ease, stroke-width 400ms ease", transition: "fill 300ms ease, stroke-width 400ms ease",
}, },
})); }));
export const IconBox = styled(Box)(({ theme }) => ({ export const IconBox = styled(Box)(({ theme }) => ({
height: 34, height: 34,
minWidth: 34, minWidth: 34,
width: 34, width: 34,
position: "relative", position: "relative",
border: 1, border: 1,
borderStyle: "solid", borderStyle: "solid",
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
borderRadius: 4, borderRadius: 4,
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
"& svg": { "& svg": {
position: "absolute", position: "absolute",
top: "50%", top: "50%",
left: "50%", left: "50%",
transform: "translate(-50%, -50%)", transform: "translate(-50%, -50%)",
width: 20, width: 20,
height: 20, height: 20,
"& path": { "& path": {
stroke: theme.palette.text.tertiary, stroke: theme.palette.text.tertiary,
}, },
}, },
})); }));
export const StatBox = styled(Box)(({ theme }) => ({ export const StatBox = styled(Box)(({ theme }) => ({
padding: `${theme.spacing(4)} ${theme.spacing(8)}`, padding: `${theme.spacing(4)} ${theme.spacing(8)}`,
minWidth: 200, minWidth: 200,
width: 225, width: 225,
border: 1, border: 1,
borderStyle: "solid", borderStyle: "solid",
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: 4, borderRadius: 4,
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
background: `linear-gradient(340deg, ${theme.palette.background.accent} 20%, ${theme.palette.background.main} 45%)`, background: `linear-gradient(340deg, ${theme.palette.background.accent} 20%, ${theme.palette.background.main} 45%)`,
"& h2": { "& h2": {
fontSize: 13, fontSize: 13,
fontWeight: 500, fontWeight: 500,
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
textTransform: "uppercase", textTransform: "uppercase",
}, },
"& p": { "& p": {
fontSize: 18, fontSize: 18,
color: theme.palette.text.primary, color: theme.palette.text.primary,
marginTop: theme.spacing(2), marginTop: theme.spacing(2),
"& span": { "& span": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
marginLeft: theme.spacing(2), marginLeft: theme.spacing(2),
fontSize: 15, fontSize: 15,
}, },
}, },
})); }));
@@ -1,17 +1,17 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import {
TableContainer, TableContainer,
Table, Table,
TableHead, TableHead,
TableRow, TableRow,
TableCell, TableCell,
TableBody, TableBody,
Paper, Paper,
Box, Box,
TablePagination, TablePagination,
Stack, Stack,
Typography, Typography,
Button, Button,
} from "@mui/material"; } from "@mui/material";
import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded";
import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded"; import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded";
@@ -48,386 +48,381 @@ import useUtils from "../../utils";
* @returns {JSX.Element} Pagination actions component. * @returns {JSX.Element} Pagination actions component.
*/ */
const TablePaginationActions = (props) => { const TablePaginationActions = (props) => {
const { count, page, rowsPerPage, onPageChange } = props; const { count, page, rowsPerPage, onPageChange } = props;
const handleFirstPageButtonClick = (event) => { const handleFirstPageButtonClick = (event) => {
onPageChange(event, 0); onPageChange(event, 0);
}; };
const handleBackButtonClick = (event) => { const handleBackButtonClick = (event) => {
onPageChange(event, page - 1); onPageChange(event, page - 1);
}; };
const handleNextButtonClick = (event) => { const handleNextButtonClick = (event) => {
onPageChange(event, page + 1); onPageChange(event, page + 1);
}; };
const handleLastPageButtonClick = (event) => { const handleLastPageButtonClick = (event) => {
onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1));
}; };
return ( return (
<Box sx={{ flexShrink: 0, ml: "24px" }}> <Box sx={{ flexShrink: 0, ml: "24px" }}>
<Button <Button
variant="group" variant="group"
onClick={handleFirstPageButtonClick} onClick={handleFirstPageButtonClick}
disabled={page === 0} disabled={page === 0}
aria-label="first page" aria-label="first page"
> >
<LeftArrowDouble /> <LeftArrowDouble />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleBackButtonClick} onClick={handleBackButtonClick}
disabled={page === 0} disabled={page === 0}
aria-label="previous page" aria-label="previous page"
> >
<LeftArrow /> <LeftArrow />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleNextButtonClick} onClick={handleNextButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1} disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="next page" aria-label="next page"
> >
<RightArrow /> <RightArrow />
</Button> </Button>
<Button <Button
variant="group" variant="group"
onClick={handleLastPageButtonClick} onClick={handleLastPageButtonClick}
disabled={page >= Math.ceil(count / rowsPerPage) - 1} disabled={page >= Math.ceil(count / rowsPerPage) - 1}
aria-label="last page" aria-label="last page"
> >
<RightArrowDouble /> <RightArrowDouble />
</Button> </Button>
</Box> </Box>
); );
}; };
TablePaginationActions.propTypes = { TablePaginationActions.propTypes = {
count: PropTypes.number.isRequired, count: PropTypes.number.isRequired,
page: PropTypes.number.isRequired, page: PropTypes.number.isRequired,
rowsPerPage: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired,
onPageChange: PropTypes.func.isRequired, onPageChange: PropTypes.func.isRequired,
}; };
const MonitorTable = ({ isAdmin, filter, setLoading }) => { const MonitorTable = ({ isAdmin, filter, setLoading }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const { determineState } = useUtils(); const { determineState } = useUtils();
const { rowsPerPage } = useSelector((state) => state.ui.monitors); const { rowsPerPage } = useSelector((state) => state.ui.monitors);
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
const [monitors, setMonitors] = useState([]); const [monitors, setMonitors] = useState([]);
const [monitorCount, setMonitorCount] = useState(0); const [monitorCount, setMonitorCount] = useState(0);
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const [updateTrigger, setUpdateTrigger] = useState(false); const [updateTrigger, setUpdateTrigger] = useState(false);
const [sort, setSort] = useState({}); const [sort, setSort] = useState({});
const prevFilter = useRef(filter); const prevFilter = useRef(filter);
const handleActionMenuDelete = () => { const handleActionMenuDelete = () => {
setUpdateTrigger((prev) => !prev); setUpdateTrigger((prev) => !prev);
}; };
const handleChangePage = (event, newPage) => { const handleChangePage = (event, newPage) => {
setPage(newPage); setPage(newPage);
}; };
const handleChangeRowsPerPage = (event) => { const handleChangeRowsPerPage = (event) => {
dispatch( dispatch(
setRowsPerPage({ setRowsPerPage({
value: parseInt(event.target.value, 10), value: parseInt(event.target.value, 10),
table: "monitors", table: "monitors",
}) })
); );
setPage(0); setPage(0);
}; };
const fetchPage = useCallback(async () => { const fetchPage = useCallback(async () => {
try { try {
const { authToken } = authState; const { authToken } = authState;
const user = jwtDecode(authToken); const user = jwtDecode(authToken);
const res = await networkService.getMonitorsByTeamId({ const res = await networkService.getMonitorsByTeamId({
authToken, authToken,
teamId: user.teamId, teamId: user.teamId,
limit: 25, limit: 25,
types: ["http", "ping"], types: ["http", "ping"],
status: null, status: null,
checkOrder: "desc", checkOrder: "desc",
normalize: true, normalize: true,
page: page, page: page,
rowsPerPage: rowsPerPage, rowsPerPage: rowsPerPage,
filter: filter, filter: filter,
field: sort.field, field: sort.field,
order: sort.order, order: sort.order,
}); });
setMonitors(res?.data?.data?.monitors ?? []); setMonitors(res?.data?.data?.monitors ?? []);
setMonitorCount(res?.data?.data?.monitorCount ?? 0); setMonitorCount(res?.data?.data?.monitorCount ?? 0);
setLoading(false); setLoading(false);
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
} }
}, [authState, page, rowsPerPage, filter, sort, setLoading]); }, [authState, page, rowsPerPage, filter, sort, setLoading]);
useEffect(() => { useEffect(() => {
fetchPage(); fetchPage();
}, [ }, [updateTrigger, authState, page, rowsPerPage, filter, sort, setLoading, fetchPage]);
updateTrigger,
authState,
page,
rowsPerPage,
filter,
sort,
setLoading,
fetchPage,
]);
// Listen for changes in filter, if new value reset the page // Listen for changes in filter, if new value reset the page
useEffect(() => { useEffect(() => {
if (prevFilter.current !== filter) { if (prevFilter.current !== filter) {
setPage(0); setPage(0);
fetchPage(); fetchPage();
} }
prevFilter.current = filter; prevFilter.current = filter;
}, [filter, fetchPage]); }, [filter, fetchPage]);
/** /**
* Helper function to calculate the range of displayed rows. * Helper function to calculate the range of displayed rows.
* @returns {string} * @returns {string}
*/ */
const getRange = () => { const getRange = () => {
let start = page * rowsPerPage + 1; let start = page * rowsPerPage + 1;
let end = Math.min(page * rowsPerPage + rowsPerPage, monitorCount); let end = Math.min(page * rowsPerPage + rowsPerPage, monitorCount);
return `${start} - ${end}`; return `${start} - ${end}`;
}; };
const handleSort = async (field) => { const handleSort = async (field) => {
let order = ""; let order = "";
if (sort.field !== field) { if (sort.field !== field) {
order = "desc"; order = "desc";
} else { } else {
order = sort.order === "asc" ? "desc" : "asc"; order = sort.order === "asc" ? "desc" : "asc";
} }
setSort({ field, order }); setSort({ field, order });
const { authToken } = authState; const { authToken } = authState;
const user = jwtDecode(authToken); const user = jwtDecode(authToken);
const res = await networkService.getMonitorsByTeamId({ const res = await networkService.getMonitorsByTeamId({
authToken, authToken,
teamId: user.teamId, teamId: user.teamId,
limit: 25, limit: 25,
types: ["http", "ping"], types: ["http", "ping"],
status: null, status: null,
checkOrder: "desc", checkOrder: "desc",
normalize: true, normalize: true,
page: page, page: page,
rowsPerPage: rowsPerPage, rowsPerPage: rowsPerPage,
filter: null, filter: null,
field: field, field: field,
order: order, order: order,
}); });
setMonitors(res?.data?.data?.monitors ?? []); setMonitors(res?.data?.data?.monitors ?? []);
setMonitorCount(res?.data?.data?.monitorCount ?? 0); setMonitorCount(res?.data?.data?.monitorCount ?? 0);
}; };
return ( return (
<> <>
<TableContainer component={Paper}> <TableContainer component={Paper}>
<Table> <Table>
<TableHead> <TableHead>
<TableRow> <TableRow>
<TableCell <TableCell
sx={{ cursor: "pointer" }} sx={{ cursor: "pointer" }}
onClick={() => handleSort("name")} onClick={() => handleSort("name")}
> >
<Box> <Box>
Host Host
<span <span
style={{ style={{
visibility: sort.field === "name" ? "visible" : "hidden", visibility: sort.field === "name" ? "visible" : "hidden",
}} }}
> >
{sort.order === "asc" ? ( {sort.order === "asc" ? (
<ArrowUpwardRoundedIcon /> <ArrowUpwardRoundedIcon />
) : ( ) : (
<ArrowDownwardRoundedIcon /> <ArrowDownwardRoundedIcon />
)} )}
</span> </span>
</Box> </Box>
</TableCell> </TableCell>
<TableCell <TableCell
sx={{ cursor: "pointer" }} sx={{ cursor: "pointer" }}
onClick={() => handleSort("status")} onClick={() => handleSort("status")}
> >
{" "} {" "}
<Box width="max-content"> <Box width="max-content">
{" "} {" "}
Status Status
<span <span
style={{ style={{
visibility: visibility: sort.field === "status" ? "visible" : "hidden",
sort.field === "status" ? "visible" : "hidden", }}
}} >
> {sort.order === "asc" ? (
{sort.order === "asc" ? ( <ArrowUpwardRoundedIcon />
<ArrowUpwardRoundedIcon /> ) : (
) : ( <ArrowDownwardRoundedIcon />
<ArrowDownwardRoundedIcon /> )}
)} </span>
</span> </Box>
</Box> </TableCell>
</TableCell> <TableCell>Response Time</TableCell>
<TableCell>Response Time</TableCell> <TableCell>Type</TableCell>
<TableCell>Type</TableCell> <TableCell>Actions</TableCell>
<TableCell>Actions</TableCell> </TableRow>
</TableRow> </TableHead>
</TableHead> <TableBody>
<TableBody> {monitors.map((monitor) => {
{monitors.map((monitor) => { let uptimePercentage = "";
let uptimePercentage = ""; let percentageColor = theme.palette.percentage.uptimeExcellent;
let percentageColor = theme.palette.percentage.uptimeExcellent;
// Determine uptime percentage and color based on the monitor's uptimePercentage value // Determine uptime percentage and color based on the monitor's uptimePercentage value
if (monitor.uptimePercentage !== undefined) { if (monitor.uptimePercentage !== undefined) {
uptimePercentage = uptimePercentage =
monitor.uptimePercentage === 0 monitor.uptimePercentage === 0
? "0" ? "0"
: (monitor.uptimePercentage * 100).toFixed(2); : (monitor.uptimePercentage * 100).toFixed(2);
percentageColor = percentageColor =
monitor.uptimePercentage < 0.25 monitor.uptimePercentage < 0.25
? theme.palette.percentage.uptimePoor ? theme.palette.percentage.uptimePoor
: monitor.uptimePercentage < 0.5 : monitor.uptimePercentage < 0.5
? theme.palette.percentage.uptimeFair ? theme.palette.percentage.uptimeFair
: monitor.uptimePercentage < 0.75 : monitor.uptimePercentage < 0.75
? theme.palette.percentage.uptimeGood ? theme.palette.percentage.uptimeGood
: theme.palette.percentage.uptimeExcellent; : theme.palette.percentage.uptimeExcellent;
} }
const params = { const params = {
url: monitor.url, url: monitor.url,
title: monitor.name, title: monitor.name,
percentage: uptimePercentage, percentage: uptimePercentage,
percentageColor, percentageColor,
status: determineState(monitor), status: determineState(monitor),
}; };
return ( return (
<TableRow <TableRow
key={monitor._id} key={monitor._id}
sx={{ sx={{
cursor: "pointer", cursor: "pointer",
"&:hover": { "&:hover": {
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
}, },
}} }}
onClick={() => { onClick={() => {
navigate(`/monitors/${monitor._id}`); navigate(`/monitors/${monitor._id}`);
}} }}
> >
<TableCell> <TableCell>
<Host key={monitor._id} params={params} /> <Host
</TableCell> key={monitor._id}
<TableCell> params={params}
<StatusLabel />
status={params.status} </TableCell>
text={params.status} <TableCell>
customStyles={{ textTransform: "capitalize" }} <StatusLabel
/> status={params.status}
</TableCell> text={params.status}
<TableCell> customStyles={{ textTransform: "capitalize" }}
<BarChart checks={monitor.checks.slice().reverse()} /> />
</TableCell> </TableCell>
<TableCell> <TableCell>
<span style={{ textTransform: "uppercase" }}> <BarChart checks={monitor.checks.slice().reverse()} />
{monitor.type} </TableCell>
</span> <TableCell>
</TableCell> <span style={{ textTransform: "uppercase" }}>{monitor.type}</span>
<TableCell> </TableCell>
<ActionsMenu <TableCell>
monitor={monitor} <ActionsMenu
isAdmin={isAdmin} monitor={monitor}
updateCallback={handleActionMenuDelete} isAdmin={isAdmin}
/> updateCallback={handleActionMenuDelete}
</TableCell> />
</TableRow> </TableCell>
); </TableRow>
})} );
</TableBody> })}
</Table> </TableBody>
</TableContainer> </Table>
<Stack </TableContainer>
direction="row" <Stack
alignItems="center" direction="row"
justifyContent="space-between" alignItems="center"
px={theme.spacing(4)} justifyContent="space-between"
> px={theme.spacing(4)}
<Typography px={theme.spacing(2)} variant="body2" sx={{ opacity: 0.7 }}> >
Showing {getRange()} of {monitorCount} monitor(s) <Typography
</Typography> px={theme.spacing(2)}
<TablePagination variant="body2"
component="div" sx={{ opacity: 0.7 }}
count={monitorCount} >
page={page} Showing {getRange()} of {monitorCount} monitor(s)
onPageChange={handleChangePage} </Typography>
rowsPerPage={rowsPerPage} <TablePagination
rowsPerPageOptions={[5, 10, 15, 25]} component="div"
onRowsPerPageChange={handleChangeRowsPerPage} count={monitorCount}
ActionsComponent={TablePaginationActions} page={page}
labelRowsPerPage="Rows per page" onPageChange={handleChangePage}
labelDisplayedRows={({ page, count }) => rowsPerPage={rowsPerPage}
`Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}` rowsPerPageOptions={[5, 10, 15, 25]}
} onRowsPerPageChange={handleChangeRowsPerPage}
slotProps={{ ActionsComponent={TablePaginationActions}
select: { labelRowsPerPage="Rows per page"
MenuProps: { labelDisplayedRows={({ page, count }) =>
keepMounted: true, `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
disableScrollLock: true, }
PaperProps: { slotProps={{
className: "pagination-dropdown", select: {
sx: { MenuProps: {
mt: 0, keepMounted: true,
mb: theme.spacing(2), disableScrollLock: true,
}, PaperProps: {
}, className: "pagination-dropdown",
transformOrigin: { vertical: "bottom", horizontal: "left" }, sx: {
anchorOrigin: { vertical: "top", horizontal: "left" }, mt: 0,
sx: { mt: theme.spacing(-2) }, mb: theme.spacing(2),
}, },
inputProps: { id: "pagination-dropdown" }, },
IconComponent: SelectorVertical, transformOrigin: { vertical: "bottom", horizontal: "left" },
sx: { anchorOrigin: { vertical: "top", horizontal: "left" },
ml: theme.spacing(4), sx: { mt: theme.spacing(-2) },
mr: theme.spacing(12), },
minWidth: theme.spacing(20), inputProps: { id: "pagination-dropdown" },
textAlign: "left", IconComponent: SelectorVertical,
"&.Mui-focused > div": { sx: {
backgroundColor: theme.palette.background.main, ml: theme.spacing(4),
}, mr: theme.spacing(12),
}, minWidth: theme.spacing(20),
}, textAlign: "left",
}} "&.Mui-focused > div": {
sx={{ backgroundColor: theme.palette.background.main,
mt: theme.spacing(6), },
color: theme.palette.text.secondary, },
"& svg path": { },
stroke: theme.palette.text.tertiary, }}
strokeWidth: 1.3, sx={{
}, mt: theme.spacing(6),
"& .MuiSelect-select": { color: theme.palette.text.secondary,
border: 1, "& svg path": {
borderColor: theme.palette.border.light, stroke: theme.palette.text.tertiary,
borderRadius: theme.shape.borderRadius, strokeWidth: 1.3,
}, },
}} "& .MuiSelect-select": {
/> border: 1,
</Stack> borderColor: theme.palette.border.light,
</> borderRadius: theme.shape.borderRadius,
); },
}}
/>
</Stack>
</>
);
}; };
MonitorTable.propTypes = { MonitorTable.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
filter: PropTypes.string, filter: PropTypes.string,
setLoading: PropTypes.func, setLoading: PropTypes.func,
}; };
const MemoizedMonitorTable = memo(MonitorTable); const MemoizedMonitorTable = memo(MonitorTable);
+94 -94
View File
@@ -6,106 +6,106 @@ import Background from "../../../assets/Images/background-grid.svg?react";
import ClockSnooze from "../../../assets/icons/clock-snooze.svg?react"; import ClockSnooze from "../../../assets/icons/clock-snooze.svg?react";
const StatusBox = ({ title, value }) => { const StatusBox = ({ title, value }) => {
const theme = useTheme(); const theme = useTheme();
let sharedStyles = { let sharedStyles = {
position: "absolute", position: "absolute",
right: 8, right: 8,
opacity: 0.5, opacity: 0.5,
"& svg path": { stroke: theme.palette.other.icon }, "& svg path": { stroke: theme.palette.other.icon },
}; };
let color; let color;
let icon; let icon;
if (title === "up") { if (title === "up") {
color = theme.palette.success.main; color = theme.palette.success.main;
icon = ( icon = (
<Box sx={{ ...sharedStyles, top: 8 }}> <Box sx={{ ...sharedStyles, top: 8 }}>
<Arrow /> <Arrow />
</Box> </Box>
); );
} else if (title === "down") { } else if (title === "down") {
color = theme.palette.error.text; color = theme.palette.error.text;
icon = ( icon = (
<Box sx={{ ...sharedStyles, transform: "rotate(180deg)", top: 5 }}> <Box sx={{ ...sharedStyles, transform: "rotate(180deg)", top: 5 }}>
<Arrow /> <Arrow />
</Box> </Box>
); );
} else if (title === "paused") { } else if (title === "paused") {
color = theme.palette.warning.main; color = theme.palette.warning.main;
icon = ( icon = (
<Box sx={{ ...sharedStyles, top: 12, right: 12 }}> <Box sx={{ ...sharedStyles, top: 12, right: 12 }}>
<ClockSnooze /> <ClockSnooze />
</Box> </Box>
); );
} }
return ( return (
<Box <Box
position="relative" position="relative"
flex={1} flex={1}
border={1} border={1}
borderColor={theme.palette.border.light} borderColor={theme.palette.border.light}
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
backgroundColor={theme.palette.background.main} backgroundColor={theme.palette.background.main}
p={theme.spacing(8)} p={theme.spacing(8)}
overflow="hidden" overflow="hidden"
sx={{ sx={{
"&:hover": { "&:hover": {
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
}, },
}} }}
> >
<Box <Box
sx={{ sx={{
position: "absolute", position: "absolute",
top: "-10%", top: "-10%",
left: "5%", left: "5%",
pointerEvents: "none", pointerEvents: "none",
"& svg g g:last-of-type path": { "& svg g g:last-of-type path": {
stroke: theme.palette.other.grid, stroke: theme.palette.other.grid,
}, },
}} }}
> >
<Background /> <Background />
</Box> </Box>
<Box <Box
textTransform="uppercase" textTransform="uppercase"
fontSize={15} fontSize={15}
letterSpacing={0.5} letterSpacing={0.5}
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
mb={theme.spacing(8)} mb={theme.spacing(8)}
sx={{ opacity: 0.6 }} sx={{ opacity: 0.6 }}
> >
{title} {title}
</Box> </Box>
{icon} {icon}
<Stack <Stack
direction="row" direction="row"
alignItems="flex-start" alignItems="flex-start"
fontSize={36} fontSize={36}
fontWeight={600} fontWeight={600}
color={color} color={color}
gap="2px" gap="2px"
> >
{value} {value}
<Typography <Typography
component="span" component="span"
fontSize={20} fontSize={20}
fontWeight={300} fontWeight={300}
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
sx={{ opacity: 0.3 }} sx={{ opacity: 0.3 }}
> >
# #
</Typography> </Typography>
</Stack> </Stack>
</Box> </Box>
); );
}; };
StatusBox.propTypes = { StatusBox.propTypes = {
title: PropTypes.oneOf(["up", "down", "paused"]).isRequired, title: PropTypes.oneOf(["up", "down", "paused"]).isRequired,
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
}; };
export default StatusBox; export default StatusBox;
+199 -203
View File
@@ -4,226 +4,222 @@ import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { IconButton, Menu, MenuItem } from "@mui/material";
import { import {
IconButton, deleteUptimeMonitor,
Menu, pauseUptimeMonitor,
MenuItem getUptimeMonitorsByTeamId,
} from "@mui/material";
import {
deleteUptimeMonitor,
pauseUptimeMonitor,
getUptimeMonitorsByTeamId,
} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import Settings from "../../../assets/icons/settings-bold.svg?react"; import Settings from "../../../assets/icons/settings-bold.svg?react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import Dialog from "../../../Components/Dialog" import Dialog from "../../../Components/Dialog";
const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
const [actions, setActions] = useState({}); const [actions, setActions] = useState({});
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const dispatch = useDispatch(); const dispatch = useDispatch();
const theme = useTheme(); const theme = useTheme();
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const authToken = authState.authToken; const authToken = authState.authToken;
const { isLoading } = useSelector((state) => state.uptimeMonitors); const { isLoading } = useSelector((state) => state.uptimeMonitors);
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
let monitor = { _id: actions.id }; let monitor = { _id: actions.id };
const action = await dispatch( const action = await dispatch(
deleteUptimeMonitor({ authToken: authState.authToken, monitor }) deleteUptimeMonitor({ authToken: authState.authToken, monitor })
); );
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
setIsOpen(false); // close modal setIsOpen(false); // close modal
dispatch(getUptimeMonitorsByTeamId(authState.authToken)); dispatch(getUptimeMonitorsByTeamId(authState.authToken));
updateCallback(); updateCallback();
createToast({ body: "Monitor deleted successfully." }); createToast({ body: "Monitor deleted successfully." });
} else { } else {
createToast({ body: "Failed to delete monitor." }); createToast({ body: "Failed to delete monitor." });
} }
}; };
const handlePause = async () => { const handlePause = async () => {
try { try {
const action = await dispatch( const action = await dispatch(
pauseUptimeMonitor({ authToken, monitorId: monitor._id }) pauseUptimeMonitor({ authToken, monitorId: monitor._id })
); );
if (pauseUptimeMonitor.fulfilled.match(action)) { if (pauseUptimeMonitor.fulfilled.match(action)) {
updateCallback(); updateCallback();
const state = action?.payload?.data.isActive === false ? "paused" : "resumed"; const state = action?.payload?.data.isActive === false ? "paused" : "resumed";
createToast({ body: `Monitor ${state} successfully.` }); createToast({ body: `Monitor ${state} successfully.` });
} else { } else {
throw new Error(action?.error?.message ?? "Failed to pause monitor."); throw new Error(action?.error?.message ?? "Failed to pause monitor.");
} }
} catch (error) { } catch (error) {
logger.error("Error pausing monitor:", monitor._id, error); logger.error("Error pausing monitor:", monitor._id, error);
createToast({ body: "Failed to pause monitor." }); createToast({ body: "Failed to pause monitor." });
} }
}; };
const openMenu = (event, id, url) => { const openMenu = (event, id, url) => {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
setAnchorEl(event.currentTarget); setAnchorEl(event.currentTarget);
setActions({ id: id, url: url }); setActions({ id: id, url: url });
}; };
const openRemove = (e) => { const openRemove = (e) => {
closeMenu(e); closeMenu(e);
setIsOpen(true); setIsOpen(true);
}; };
const closeMenu = (e) => { const closeMenu = (e) => {
e.stopPropagation(); e.stopPropagation();
setAnchorEl(null); setAnchorEl(null);
}; };
const navigate = useNavigate(); const navigate = useNavigate();
return ( return (
<> <>
<IconButton <IconButton
aria-label="monitor actions" aria-label="monitor actions"
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
openMenu( openMenu(event, monitor._id, monitor.type === "ping" ? null : monitor.url);
event, }}
monitor._id, sx={{
monitor.type === "ping" ? null : monitor.url "&:focus": {
); outline: "none",
}} },
sx={{ "& svg path": {
"&:focus": { stroke: theme.palette.other.icon,
outline: "none", },
}, }}
"& svg path": { >
stroke: theme.palette.other.icon, <Settings />
}, </IconButton>
}}
>
<Settings />
</IconButton>
<Menu <Menu
className="actions-menu" className="actions-menu"
anchorEl={anchorEl} anchorEl={anchorEl}
open={Boolean(anchorEl)} open={Boolean(anchorEl)}
onClose={(e) => closeMenu(e)} onClose={(e) => closeMenu(e)}
disableScrollLock disableScrollLock
slotProps={{ slotProps={{
paper: { paper: {
sx: { sx: {
"& ul": { p: theme.spacing(2.5) }, "& ul": { p: theme.spacing(2.5) },
"& li": { m: 0 }, "& li": { m: 0 },
"& li:last-of-type": { "& li:last-of-type": {
color: theme.palette.error.text, color: theme.palette.error.text,
}, },
}, },
}, },
}} }}
> >
{actions.url !== null ? ( {actions.url !== null ? (
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
closeMenu(e); closeMenu(e);
e.stopPropagation(); e.stopPropagation();
window.open(actions.url, "_blank", "noreferrer"); window.open(actions.url, "_blank", "noreferrer");
}} }}
> >
Open site Open site
</MenuItem> </MenuItem>
) : ( ) : (
"" ""
)} )}
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/monitors/${actions.id}`); navigate(`/monitors/${actions.id}`);
}} }}
> >
Details Details
</MenuItem> </MenuItem>
{/* TODO - pass monitor id to Incidents page */} {/* TODO - pass monitor id to Incidents page */}
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/incidents/${actions.id}`); navigate(`/incidents/${actions.id}`);
}} }}
> >
Incidents Incidents
</MenuItem> </MenuItem>
{isAdmin && ( {isAdmin && (
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/monitors/configure/${actions.id}`); navigate(`/monitors/configure/${actions.id}`);
}} }}
> >
Configure Configure
</MenuItem> </MenuItem>
)} )}
{isAdmin && ( {isAdmin && (
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/monitors/create/${actions.id}`); navigate(`/monitors/create/${actions.id}`);
}} }}
> >
Clone Clone
</MenuItem> </MenuItem>
)} )}
{isAdmin && ( {isAdmin && (
<MenuItem <MenuItem
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
handlePause(e); handlePause(e);
}} }}
> >
{monitor?.isActive === true ? "Pause" : "Resume"} {monitor?.isActive === true ? "Pause" : "Resume"}
</MenuItem>
</MenuItem> )}
)} {isAdmin && (
{isAdmin && ( <MenuItem
<MenuItem onClick={(e) => {
onClick={(e) => { e.stopPropagation();
e.stopPropagation(); openRemove(e);
openRemove(e); }}
}} >
> Remove
Remove </MenuItem>
</MenuItem> )}
)} </Menu>
</Menu> <Dialog
<Dialog modelTitle="modal-delete-monitor"
modelTitle="modal-delete-monitor" modelDescription="delete-monitor-confirmation"
modelDescription="delete-monitor-confirmation" open={isOpen}
open={isOpen} onClose={() => setIsOpen(false)}
onClose={() => setIsOpen(false)} title="Do you really want to delete this monitor?"
title="Do you really want to delete this monitor?" confirmationBtnLbl="Delete"
confirmationBtnLbl="Delete" confirmationBtnOnClick={(e) => {
confirmationBtnOnClick={e => { e.stopPropagation(); handleRemove(e) }} e.stopPropagation();
cancelBtnLbl="Cancel" handleRemove(e);
cancelBtnOnClick={e => { e.stopPropagation(); setIsOpen(false) }} }}
theme={theme} cancelBtnLbl="Cancel"
isLoading={isLoading} cancelBtnOnClick={(e) => {
description="Once deleted, this monitor cannot be retrieved." e.stopPropagation();
> setIsOpen(false);
</Dialog> }}
</> theme={theme}
); isLoading={isLoading}
description="Once deleted, this monitor cannot be retrieved."
></Dialog>
</>
);
}; };
ActionsMenu.propTypes = { ActionsMenu.propTypes = {
monitor: PropTypes.shape({ monitor: PropTypes.shape({
_id: PropTypes.string, _id: PropTypes.string,
url: PropTypes.string, url: PropTypes.string,
type: PropTypes.string, type: PropTypes.string,
isActive: PropTypes.bool, isActive: PropTypes.bool,
}).isRequired, }).isRequired,
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
updateCallback: PropTypes.func, updateCallback: PropTypes.func,
}; };
export default ActionsMenu; export default ActionsMenu;
+43 -39
View File
@@ -7,49 +7,53 @@ import PlaceholderDark from "../../../assets/Images/data_placeholder_dark.svg?re
import PropTypes from "prop-types"; import PropTypes from "prop-types";
const Fallback = ({ isAdmin }) => { const Fallback = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const mode = useSelector((state) => state.ui.mode); const mode = useSelector((state) => state.ui.mode);
return ( return (
<Stack <Stack
alignItems="center" alignItems="center"
backgroundColor={theme.palette.background.main} backgroundColor={theme.palette.background.main}
p={theme.spacing(30)} p={theme.spacing(30)}
pt={theme.spacing(25)} pt={theme.spacing(25)}
gap={theme.spacing(2)} gap={theme.spacing(2)}
border={1} border={1}
borderRadius={theme.shape.borderRadius} borderRadius={theme.shape.borderRadius}
borderColor={theme.palette.border.light} borderColor={theme.palette.border.light}
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
> >
<Box pb={theme.spacing(20)}> <Box pb={theme.spacing(20)}>
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />} {mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box> </Box>
<Typography component="h2" variant="h2" fontWeight={500}> <Typography
No monitors found to display component="h2"
</Typography> variant="h2"
<Typography variant="body1"> fontWeight={500}
It looks like you don’t have any monitors set up yet. >
</Typography> No monitors found to display
{isAdmin && ( </Typography>
<Button <Typography variant="body1">
variant="contained" It looks like you don’t have any monitors set up yet.
color="primary" </Typography>
onClick={() => { {isAdmin && (
navigate("/monitors/create"); <Button
}} variant="contained"
sx={{ mt: theme.spacing(12) }} color="primary"
> onClick={() => {
Create your first monitor navigate("/monitors/create");
</Button> }}
)} sx={{ mt: theme.spacing(12) }}
</Stack> >
); Create your first monitor
</Button>
)}
</Stack>
);
}; };
Fallback.propTypes = { Fallback.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
}; };
export default Fallback; export default Fallback;
+41 -41
View File
@@ -12,50 +12,50 @@ import PropTypes from "prop-types";
* @returns {React.ElementType} Returns a div element with the host details. * @returns {React.ElementType} Returns a div element with the host details.
*/ */
const Host = ({ params }) => { const Host = ({ params }) => {
return ( return (
<Box className="host"> <Box className="host">
<Box <Box
display="inline-block" display="inline-block"
position="relative" position="relative"
sx={{ sx={{
fontWeight: 500, fontWeight: 500,
"&:before": { "&:before": {
position: "absolute", position: "absolute",
content: `""`, content: `""`,
width: "4px", width: "4px",
height: "4px", height: "4px",
borderRadius: "50%", borderRadius: "50%",
backgroundColor: "gray", backgroundColor: "gray",
opacity: 0.8, opacity: 0.8,
right: "-10px", right: "-10px",
top: "42%", top: "42%",
}, },
}} }}
> >
{params.title} {params.title}
</Box> </Box>
<Typography <Typography
component="span" component="span"
sx={{ sx={{
color: params.percentageColor, color: params.percentageColor,
fontWeight: 500, fontWeight: 500,
ml: "15px", ml: "15px",
}} }}
> >
{params.percentage}% {params.percentage}%
</Typography> </Typography>
<Box sx={{ opacity: 0.6 }}>{params.url}</Box> <Box sx={{ opacity: 0.6 }}>{params.url}</Box>
</Box> </Box>
); );
}; };
Host.propTypes = { Host.propTypes = {
params: PropTypes.shape({ params: PropTypes.shape({
title: PropTypes.string, title: PropTypes.string,
percentageColor: PropTypes.string, percentageColor: PropTypes.string,
percentage: PropTypes.string, percentage: PropTypes.string,
url: PropTypes.string, url: PropTypes.string,
}).isRequired, }).isRequired,
}; };
export default Host; export default Host;
+14 -14
View File
@@ -1,19 +1,19 @@
.monitors .MuiStack-root > button:not(.MuiIconButton-root) { .monitors .MuiStack-root > button:not(.MuiIconButton-root) {
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
height: var(--env-var-height-2); height: var(--env-var-height-2);
min-width: fit-content; min-width: fit-content;
} }
.current-monitors-counter { .current-monitors-counter {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
padding: 5px; padding: 5px;
min-width: 25px; min-width: 25px;
min-height: 25px; min-height: 25px;
border-radius: 50%; border-radius: 50%;
font-size: var(--env-var-font-size-medium); font-size: var(--env-var-font-size-medium);
font-weight: 500; font-weight: 500;
margin-left: 10px; margin-left: 10px;
line-height: 0.8; line-height: 0.8;
} }
+162 -167
View File
@@ -4,13 +4,7 @@ import { useSelector, useDispatch } from "react-redux";
import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { getUptimeMonitorsByTeamId } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { import { Box, Button, CircularProgress, Stack, Typography } from "@mui/material";
Box,
Button,
CircularProgress,
Stack,
Typography,
} from "@mui/material";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import Fallback from "./fallback"; import Fallback from "./fallback";
@@ -22,173 +16,174 @@ import Search from "../../../Components/Inputs/Search";
import useDebounce from "../../../Utils/debounce"; import useDebounce from "../../../Utils/debounce";
const Monitors = ({ isAdmin }) => { const Monitors = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const monitorState = useSelector((state) => state.uptimeMonitors); const monitorState = useSelector((state) => state.uptimeMonitors);
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [isSearching, setIsSearching] = useState(false); const [isSearching, setIsSearching] = useState(false);
const dispatch = useDispatch({}); const dispatch = useDispatch({});
const debouncedFilter = useDebounce(search, 500); const debouncedFilter = useDebounce(search, 500);
const handleSearch = (value) => { const handleSearch = (value) => {
setIsSearching(true); setIsSearching(true);
setSearch(value); setSearch(value);
}; };
useEffect(() => { useEffect(() => {
dispatch(getUptimeMonitorsByTeamId(authState.authToken)); dispatch(getUptimeMonitorsByTeamId(authState.authToken));
}, [authState.authToken, dispatch]); }, [authState.authToken, dispatch]);
let loading = let loading =
monitorState?.isLoading && monitorState?.isLoading && monitorState?.monitorsSummary?.monitors?.length === 0;
monitorState?.monitorsSummary?.monitors?.length === 0;
return ( return (
<Stack className="monitors table-container" gap={theme.spacing(8)}> <Stack
{loading ? ( className="monitors table-container"
<SkeletonLayout /> gap={theme.spacing(8)}
) : ( >
<> {loading ? (
<Box> <SkeletonLayout />
<Breadcrumbs list={[{ name: `monitors`, path: "/monitors" }]} /> ) : (
<Stack <>
direction="row" <Box>
justifyContent="space-between" <Breadcrumbs list={[{ name: `monitors`, path: "/monitors" }]} />
alignItems="center" <Stack
mt={theme.spacing(5)} direction="row"
> justifyContent="space-between"
<Greeting type="uptime" /> alignItems="center"
{isAdmin && mt={theme.spacing(5)}
monitorState?.monitorsSummary?.monitors?.length !== 0 && ( >
<Button <Greeting type="uptime" />
variant="contained" {isAdmin && monitorState?.monitorsSummary?.monitors?.length !== 0 && (
color="primary" <Button
onClick={() => { variant="contained"
navigate("/monitors/create"); color="primary"
}} onClick={() => {
sx={{ fontWeight: 500 }} navigate("/monitors/create");
> }}
Create monitor sx={{ fontWeight: 500 }}
</Button> >
)} Create monitor
</Stack> </Button>
</Box> )}
{isAdmin && monitorState?.monitorsSummary?.monitors?.length === 0 && ( </Stack>
<Fallback isAdmin={isAdmin} /> </Box>
)} {isAdmin && monitorState?.monitorsSummary?.monitors?.length === 0 && (
<Fallback isAdmin={isAdmin} />
)}
{monitorState?.monitorsSummary?.monitors?.length !== 0 && ( {monitorState?.monitorsSummary?.monitors?.length !== 0 && (
<> <>
<Stack <Stack
gap={theme.spacing(8)} gap={theme.spacing(8)}
direction="row" direction="row"
justifyContent="space-between" justifyContent="space-between"
> >
<StatusBox <StatusBox
title="up" title="up"
value={monitorState?.monitorsSummary?.monitorCounts?.up ?? 0} value={monitorState?.monitorsSummary?.monitorCounts?.up ?? 0}
/> />
<StatusBox <StatusBox
title="down" title="down"
value={ value={monitorState?.monitorsSummary?.monitorCounts?.down ?? 0}
monitorState?.monitorsSummary?.monitorCounts?.down ?? 0 />
} <StatusBox
/> title="paused"
<StatusBox value={monitorState?.monitorsSummary?.monitorCounts?.paused ?? 0}
title="paused" />
value={ </Stack>
monitorState?.monitorsSummary?.monitorCounts?.paused ?? 0 <Box
} flex={1}
/> px={theme.spacing(10)}
</Stack> py={theme.spacing(8)}
<Box border={1}
flex={1} borderColor={theme.palette.border.light}
px={theme.spacing(10)} borderRadius={theme.shape.borderRadius}
py={theme.spacing(8)} backgroundColor={theme.palette.background.main}
border={1} >
borderColor={theme.palette.border.light} <Stack
borderRadius={theme.shape.borderRadius} direction="row"
backgroundColor={theme.palette.background.main} alignItems="center"
> mb={theme.spacing(8)}
<Stack >
direction="row" <Typography
alignItems="center" component="h2"
mb={theme.spacing(8)} variant="h2"
> fontWeight={500}
<Typography letterSpacing={-0.2}
component="h2" >
variant="h2" Actively monitoring
fontWeight={500} </Typography>
letterSpacing={-0.2} <Box
> className="current-monitors-counter"
Actively monitoring color={theme.palette.text.primary}
</Typography> border={1}
<Box borderColor={theme.palette.border.light}
className="current-monitors-counter" backgroundColor={theme.palette.background.accent}
color={theme.palette.text.primary} >
border={1} {monitorState?.monitorsSummary?.monitorCounts?.total || 0}
borderColor={theme.palette.border.light} </Box>
backgroundColor={theme.palette.background.accent} <Box
> width="25%"
{monitorState?.monitorsSummary?.monitorCounts?.total || 0} minWidth={150}
</Box> ml="auto"
<Box width="25%" minWidth={150} ml="auto"> >
<Search <Search
options={monitorState?.monitorsSummary?.monitors ?? []} options={monitorState?.monitorsSummary?.monitors ?? []}
filteredBy="name" filteredBy="name"
inputValue={search} inputValue={search}
handleInputChange={handleSearch} handleInputChange={handleSearch}
/> />
</Box> </Box>
</Stack> </Stack>
<Box position="relative"> <Box position="relative">
{isSearching && ( {isSearching && (
<> <>
<Box <Box
width="100%" width="100%"
height="100%" height="100%"
position="absolute" position="absolute"
sx={{ sx={{
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
opacity: 0.8, opacity: 0.8,
zIndex: 100, zIndex: 100,
}} }}
/> />
<Box <Box
height="100%" height="100%"
position="absolute" position="absolute"
top="20%" top="20%"
left="50%" left="50%"
sx={{ sx={{
transform: "translateX(-50%)", transform: "translateX(-50%)",
zIndex: 101, zIndex: 101,
}} }}
> >
<CircularProgress <CircularProgress
sx={{ sx={{
color: theme.palette.other.icon, color: theme.palette.other.icon,
}} }}
/> />
</Box> </Box>
</> </>
)} )}
<MonitorTable <MonitorTable
isAdmin={isAdmin} isAdmin={isAdmin}
filter={debouncedFilter} filter={debouncedFilter}
setLoading={setIsSearching} setLoading={setIsSearching}
/> />
</Box> </Box>
</Box> </Box>
</> </>
)} )}
</> </>
)} )}
</Stack> </Stack>
); );
}; };
Monitors.propTypes = { Monitors.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
}; };
export default Monitors; export default Monitors;
+48 -19
View File
@@ -7,26 +7,55 @@ import { useTheme } from "@emotion/react";
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const SkeletonLayout = () => { const SkeletonLayout = () => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<> <>
<Stack direction="row" justifyContent="space-between" alignItems="center"> <Stack
<Skeleton variant="rounded" width="50%" height={36} /> direction="row"
<Skeleton variant="rounded" width="15%" height={36} /> justifyContent="space-between"
</Stack> alignItems="center"
<Stack >
gap={theme.spacing(12)} <Skeleton
direction="row" variant="rounded"
justifyContent="space-between" width="50%"
> height={36}
<Skeleton variant="rounded" width="100%" height={100} /> />
<Skeleton variant="rounded" width="100%" height={100} /> <Skeleton
<Skeleton variant="rounded" width="100%" height={100} /> variant="rounded"
</Stack> width="15%"
<Skeleton variant="rounded" width="100%" height="100%" flex={1} /> height={36}
</> />
); </Stack>
<Stack
gap={theme.spacing(12)}
direction="row"
justifyContent="space-between"
>
<Skeleton
variant="rounded"
width="100%"
height={100}
/>
<Skeleton
variant="rounded"
width="100%"
height={100}
/>
<Skeleton
variant="rounded"
width="100%"
height={100}
/>
</Stack>
<Skeleton
variant="rounded"
width="100%"
height="100%"
flex={1}
/>
</>
);
}; };
export default SkeletonLayout; export default SkeletonLayout;
+34 -34
View File
@@ -1,38 +1,38 @@
import { Stack, styled } from "@mui/material"; import { Stack, styled } from "@mui/material";
export const ConfigBox = styled(Stack)(({ theme }) => ({ export const ConfigBox = styled(Stack)(({ theme }) => ({
flexDirection: "row", flexDirection: "row",
border: 1, border: 1,
borderStyle: "solid", borderStyle: "solid",
borderColor: theme.palette.border.light, borderColor: theme.palette.border.light,
borderRadius: theme.spacing(2), borderRadius: theme.spacing(2),
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
"& > *": { "& > *": {
paddingTop: theme.spacing(12), paddingTop: theme.spacing(12),
paddingBottom: theme.spacing(18), paddingBottom: theme.spacing(18),
}, },
"& > div:first-of-type": { "& > div:first-of-type": {
flex: 0.7, flex: 0.7,
borderRight: 1, borderRight: 1,
borderRightStyle: "solid", borderRightStyle: "solid",
borderRightColor: theme.palette.border.light, borderRightColor: theme.palette.border.light,
paddingRight: theme.spacing(15), paddingRight: theme.spacing(15),
paddingLeft: theme.spacing(15), paddingLeft: theme.spacing(15),
}, },
"& > div:last-of-type": { "& > div:last-of-type": {
flex: 1, flex: 1,
paddingRight: theme.spacing(20), paddingRight: theme.spacing(20),
paddingLeft: theme.spacing(18), paddingLeft: theme.spacing(18),
}, },
"& h2": { "& h2": {
color: theme.palette.text.secondary, color: theme.palette.text.secondary,
fontSize: 15, fontSize: 15,
fontWeight: 600, fontWeight: 600,
}, },
"& h3, & p": { "& h3, & p": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
}, },
"& p": { "& p": {
fontSize: 13, fontSize: 13,
}, },
})); }));
+78 -78
View File
@@ -1,88 +1,88 @@
import { useTheme } from "@mui/material"; import { useTheme } from "@mui/material";
const useUtils = () => { const useUtils = () => {
const theme = useTheme(); const theme = useTheme();
const determineState = (monitor) => { const determineState = (monitor) => {
if (monitor.isActive === false) return "paused"; if (monitor.isActive === false) return "paused";
if (monitor?.status === undefined) return "pending"; if (monitor?.status === undefined) return "pending";
return monitor?.status == true ? "up" : "down"; return monitor?.status == true ? "up" : "down";
}; };
const statusColor = { const statusColor = {
up: theme.palette.success.main, up: theme.palette.success.main,
down: theme.palette.error.main, down: theme.palette.error.main,
paused: theme.palette.warning.main, paused: theme.palette.warning.main,
pending: theme.palette.warning.main, pending: theme.palette.warning.main,
}; };
const statusMsg = { const statusMsg = {
up: "Your site is up.", up: "Your site is up.",
down: "Your site is down.", down: "Your site is down.",
paused: "Pending...", paused: "Pending...",
}; };
const pagespeedStatusMsg = { const pagespeedStatusMsg = {
up: "Live (collecting data)", up: "Live (collecting data)",
down: "Inactive", down: "Inactive",
paused: "Paused", paused: "Paused",
}; };
const statusStyles = { const statusStyles = {
up: { up: {
backgroundColor: theme.palette.success.bg, backgroundColor: theme.palette.success.bg,
background: `linear-gradient(340deg, ${theme.palette.success.light} -60%, ${theme.palette.success.bg} 35%)`, background: `linear-gradient(340deg, ${theme.palette.success.light} -60%, ${theme.palette.success.bg} 35%)`,
borderColor: theme.palette.success.light, borderColor: theme.palette.success.light,
"& h2": { color: theme.palette.success.main }, "& h2": { color: theme.palette.success.main },
}, },
down: { down: {
backgroundColor: theme.palette.error.bg, backgroundColor: theme.palette.error.bg,
background: `linear-gradient(340deg, ${theme.palette.error.light} -60%, ${theme.palette.error.bg} 35%)`, background: `linear-gradient(340deg, ${theme.palette.error.light} -60%, ${theme.palette.error.bg} 35%)`,
borderColor: theme.palette.error.light, borderColor: theme.palette.error.light,
"& h2": { color: theme.palette.error.main }, "& h2": { color: theme.palette.error.main },
}, },
paused: { paused: {
backgroundColor: theme.palette.warning.bg, backgroundColor: theme.palette.warning.bg,
background: `linear-gradient(340deg, ${theme.palette.warning.light} -60%, ${theme.palette.warning.bg} 35%)`, background: `linear-gradient(340deg, ${theme.palette.warning.light} -60%, ${theme.palette.warning.bg} 35%)`,
borderColor: theme.palette.warning.light, borderColor: theme.palette.warning.light,
"& h2": { color: theme.palette.warning.main }, "& h2": { color: theme.palette.warning.main },
}, },
pending: { pending: {
backgroundColor: theme.palette.warning.light, backgroundColor: theme.palette.warning.light,
background: `linear-gradient(340deg, ${theme.palette.warning.dark} -60%, ${theme.palette.warning.light} 35%)`, background: `linear-gradient(340deg, ${theme.palette.warning.dark} -60%, ${theme.palette.warning.light} 35%)`,
borderColor: theme.palette.warning.dark, borderColor: theme.palette.warning.dark,
"& h2": { color: theme.palette.warning.main }, "& h2": { color: theme.palette.warning.main },
}, },
}; };
const pagespeedStyles = { const pagespeedStyles = {
up: { up: {
bg: theme.palette.success.bg, bg: theme.palette.success.bg,
light: theme.palette.success.light, light: theme.palette.success.light,
stroke: theme.palette.success.main, stroke: theme.palette.success.main,
}, },
down: { down: {
bg: theme.palette.error.bg, bg: theme.palette.error.bg,
light: theme.palette.error.light, light: theme.palette.error.light,
stroke: theme.palette.error.main, stroke: theme.palette.error.main,
}, },
paused: { paused: {
bg: theme.palette.warning.bg, bg: theme.palette.warning.bg,
light: theme.palette.warning.light, light: theme.palette.warning.light,
stroke: theme.palette.warning.main, stroke: theme.palette.warning.main,
}, },
pending: { pending: {
bg: theme.palette.warning.bg, bg: theme.palette.warning.bg,
light: theme.palette.warning.light, light: theme.palette.warning.light,
stroke: theme.palette.warning.main, stroke: theme.palette.warning.main,
}, },
}; };
return { return {
determineState, determineState,
statusColor, statusColor,
statusMsg, statusMsg,
pagespeedStatusMsg, pagespeedStatusMsg,
pagespeedStyles, pagespeedStyles,
statusStyles, statusStyles,
}; };
}; };
export default useUtils; export default useUtils;
+39 -25
View File
@@ -10,8 +10,8 @@ import { useTheme } from "@emotion/react";
* So That why we're using JavaScript default parameters instead. * So That why we're using JavaScript default parameters instead.
*/ */
const DefaultValue = { const DefaultValue = {
title: "Oh no! You dropped your sushi!", title: "Oh no! You dropped your sushi!",
desc: "Either the URL doesn’t exist, or you don’t have access to it.", desc: "Either the URL doesn’t exist, or you don’t have access to it.",
}; };
/** /**
@@ -31,33 +31,47 @@ const DefaultValue = {
* @returns {JSX.Element} The rendered error page component. * @returns {JSX.Element} The rendered error page component.
*/ */
const NotFound = ({ title = DefaultValue.title, desc = DefaultValue.desc }) => { const NotFound = ({ title = DefaultValue.title, desc = DefaultValue.desc }) => {
const navigate = useNavigate(); const navigate = useNavigate();
const theme = useTheme(); const theme = useTheme();
return ( return (
<Stack height="100vh" justifyContent="center"> <Stack
<Stack gap={theme.spacing(2)} alignItems="center"> height="100vh"
<img src={NotFoundSvg} alt="404" style={{ maxHeight: "25rem" }} /> justifyContent="center"
<Typography component="h1" variant="h1" fontSize={16}> >
{title} <Stack
</Typography> gap={theme.spacing(2)}
<Typography variant="body1">{desc}</Typography> alignItems="center"
<Button >
variant="contained" <img
color="primary" src={NotFoundSvg}
sx={{ mt: theme.spacing(10) }} alt="404"
onClick={() => navigate("/")} style={{ maxHeight: "25rem" }}
> />
Go to the main dashboard <Typography
</Button> component="h1"
</Stack> variant="h1"
</Stack> fontSize={16}
); >
{title}
</Typography>
<Typography variant="body1">{desc}</Typography>
<Button
variant="contained"
color="primary"
sx={{ mt: theme.spacing(10) }}
onClick={() => navigate("/")}
>
Go to the main dashboard
</Button>
</Stack>
</Stack>
);
}; };
NotFound.propTypes = { NotFound.propTypes = {
title: PropTypes.string, title: PropTypes.string,
desc: PropTypes.string, desc: PropTypes.string,
}; };
export default NotFound; export default NotFound;
@@ -1,9 +1,9 @@
.configure-pagespeed button { .configure-pagespeed button {
height: var(--env-var-height-2); height: var(--env-var-height-2);
} }
.configure-pagespeed .field, .configure-pagespeed .field,
.configure-pagespeed .section-disabled, .configure-pagespeed .section-disabled,
.configure-pagespeed .select-wrapper { .configure-pagespeed .select-wrapper {
flex: 1; flex: 1;
} }
+459 -443
View File
@@ -4,11 +4,11 @@ import { Box, Button, Modal, Stack, Tooltip, Typography } from "@mui/material";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { import {
deletePageSpeed, deletePageSpeed,
getPagespeedMonitorById, getPagespeedMonitorById,
getPageSpeedByTeamId, getPageSpeedByTeamId,
updatePageSpeed, updatePageSpeed,
pausePageSpeed, pausePageSpeed,
} from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; } from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice";
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
@@ -27,456 +27,472 @@ import useUtils from "../../Monitors/utils";
import "./index.css"; import "./index.css";
const PageSpeedConfigure = () => { const PageSpeedConfigure = () => {
const theme = useTheme(); const theme = useTheme();
const navigate = useNavigate(); const navigate = useNavigate();
const dispatch = useDispatch(); const dispatch = useDispatch();
const MS_PER_MINUTE = 60000; const MS_PER_MINUTE = 60000;
const { user, authToken } = useSelector((state) => state.auth); const { user, authToken } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors); const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
const { monitorId } = useParams(); const { monitorId } = useParams();
const [monitor, setMonitor] = useState({}); const [monitor, setMonitor] = useState({});
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const { statusColor, pagespeedStatusMsg, determineState } = useUtils(); const { statusColor, pagespeedStatusMsg, determineState } = useUtils();
const idMap = { const idMap = {
"monitor-url": "url", "monitor-url": "url",
"monitor-name": "name", "monitor-name": "name",
"monitor-checks-http": "type", "monitor-checks-http": "type",
"monitor-checks-ping": "type", "monitor-checks-ping": "type",
"notify-email-default": "notification-email", "notify-email-default": "notification-email",
}; };
const frequencies = [ const frequencies = [
{ _id: 3, name: "3 minutes" }, { _id: 3, name: "3 minutes" },
{ _id: 5, name: "5 minutes" }, { _id: 5, name: "5 minutes" },
{ _id: 10, name: "10 minutes" }, { _id: 10, name: "10 minutes" },
{ _id: 20, name: "20 minutes" }, { _id: 20, name: "20 minutes" },
{ _id: 60, name: "1 hour" }, { _id: 60, name: "1 hour" },
{ _id: 1440, name: "1 day" }, { _id: 1440, name: "1 day" },
{ _id: 10080, name: "1 week" }, { _id: 10080, name: "1 week" },
]; ];
useEffect(() => { useEffect(() => {
const fetchMonitor = async () => { const fetchMonitor = async () => {
try { try {
const action = await dispatch( const action = await dispatch(getPagespeedMonitorById({ authToken, monitorId }));
getPagespeedMonitorById({ authToken, monitorId })
);
if (getPagespeedMonitorById.fulfilled.match(action)) { if (getPagespeedMonitorById.fulfilled.match(action)) {
const monitor = action.payload.data; const monitor = action.payload.data;
setMonitor(monitor); setMonitor(monitor);
} else if (getPagespeedMonitorById.rejected.match(action)) { } else if (getPagespeedMonitorById.rejected.match(action)) {
throw new Error(action.error.message); throw new Error(action.error.message);
} }
} catch (error) { } catch (error) {
logger.error("Error fetching monitor of id: " + monitorId); logger.error("Error fetching monitor of id: " + monitorId);
navigate("/not-found", { replace: true }); navigate("/not-found", { replace: true });
} }
}; };
fetchMonitor(); fetchMonitor();
}, [dispatch, authToken, monitorId, navigate]); }, [dispatch, authToken, monitorId, navigate]);
const handleChange = (event, name) => { const handleChange = (event, name) => {
let { value, id } = event.target; let { value, id } = event.target;
if (!name) name = idMap[id]; if (!name) name = idMap[id];
if (name.includes("notification-")) { if (name.includes("notification-")) {
name = name.replace("notification-", ""); name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some( let hasNotif = monitor.notifications.some(
(notification) => notification.type === name (notification) => notification.type === name
); );
setMonitor((prev) => { setMonitor((prev) => {
const notifs = [...prev.notifications]; const notifs = [...prev.notifications];
if (hasNotif) { if (hasNotif) {
return { return {
...prev, ...prev,
notifications: notifs.filter((notif) => notif.type !== name), notifications: notifs.filter((notif) => notif.type !== name),
}; };
} else { } else {
return { return {
...prev, ...prev,
notifications: [ notifications: [
...notifs, ...notifs,
name === "email" name === "email"
? { type: name, address: value } ? { type: name, address: value }
: // TODO - phone number : // TODO - phone number
{ type: name, phone: value }, { type: name, phone: value },
], ],
}; };
} }
}); });
} else { } else {
if (name === "interval") { if (name === "interval") {
value = value * MS_PER_MINUTE; value = value * MS_PER_MINUTE;
} }
setMonitor((prev) => ({ setMonitor((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
const validation = monitorValidation.validate( const validation = monitorValidation.validate(
{ [name]: value }, { [name]: value },
{ abortEarly: false } { abortEarly: false }
); );
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (validation.error) if (validation.error) updatedErrors[name] = validation.error.details[0].message;
updatedErrors[name] = validation.error.details[0].message; else delete updatedErrors[name];
else delete updatedErrors[name]; return updatedErrors;
return updatedErrors; });
}); }
} };
};
const handlePause = async () => { const handlePause = async () => {
try { try {
const action = await dispatch(pausePageSpeed({ authToken, monitorId })); const action = await dispatch(pausePageSpeed({ authToken, monitorId }));
if (pausePageSpeed.fulfilled.match(action)) { if (pausePageSpeed.fulfilled.match(action)) {
const monitor = action.payload.data; const monitor = action.payload.data;
setMonitor(monitor); setMonitor(monitor);
} else if (pausePageSpeed.rejected.match(action)) { } else if (pausePageSpeed.rejected.match(action)) {
throw new Error(action.error.message); throw new Error(action.error.message);
} }
} catch (error) { } catch (error) {
logger.error("Error pausing monitor: " + monitorId); logger.error("Error pausing monitor: " + monitorId);
createToast({ body: "Failed to pause monitor" }); createToast({ body: "Failed to pause monitor" });
} }
}; };
const handleSave = async (event) => { const handleSave = async (event) => {
event.preventDefault(); event.preventDefault();
const action = await dispatch( const action = await dispatch(updatePageSpeed({ authToken, monitor: monitor }));
updatePageSpeed({ authToken, monitor: monitor }) if (action.meta.requestStatus === "fulfilled") {
); createToast({ body: "Monitor updated successfully!" });
if (action.meta.requestStatus === "fulfilled") { dispatch(getPageSpeedByTeamId(authToken));
createToast({ body: "Monitor updated successfully!" }); } else {
dispatch(getPageSpeedByTeamId(authToken)); createToast({ body: "Failed to update monitor." });
} else { }
createToast({ body: "Failed to update monitor." }); };
}
};
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
const action = await dispatch(deletePageSpeed({ authToken, monitor })); const action = await dispatch(deletePageSpeed({ authToken, monitor }));
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
navigate("/pagespeed"); navigate("/pagespeed");
} else { } else {
createToast({ body: "Failed to delete monitor." }); createToast({ body: "Failed to delete monitor." });
} }
}; };
return ( return (
<Stack className="configure-pagespeed" gap={theme.spacing(10)}> <Stack
{Object.keys(monitor).length === 0 ? ( className="configure-pagespeed"
<SkeletonLayout /> gap={theme.spacing(10)}
) : ( >
<> {Object.keys(monitor).length === 0 ? (
<Breadcrumbs <SkeletonLayout />
list={[ ) : (
{ name: "pagespeed", path: "/pagespeed" }, <>
{ name: "details", path: `/pagespeed/${monitorId}` }, <Breadcrumbs
{ name: "configure", path: `/pagespeed/configure/${monitorId}` }, list={[
]} { name: "pagespeed", path: "/pagespeed" },
/> { name: "details", path: `/pagespeed/${monitorId}` },
<Stack { name: "configure", path: `/pagespeed/configure/${monitorId}` },
component="form" ]}
noValidate />
spellCheck="false" <Stack
onSubmit={handleSave} component="form"
flex={1} noValidate
gap={theme.spacing(10)} spellCheck="false"
> onSubmit={handleSave}
<Stack direction="row" gap={theme.spacing(2)}> flex={1}
<Box> gap={theme.spacing(10)}
<Typography component="h1" variant="h1"> >
{monitor.name} <Stack
</Typography> direction="row"
<Stack gap={theme.spacing(2)}
direction="row" >
alignItems="center" <Box>
height="fit-content" <Typography
gap={theme.spacing(2)} component="h1"
> variant="h1"
<Tooltip >
title={pagespeedStatusMsg[determineState(monitor)]} {monitor.name}
disableInteractive </Typography>
slotProps={{ <Stack
popper: { direction="row"
modifiers: [ alignItems="center"
{ height="fit-content"
name: "offset", gap={theme.spacing(2)}
options: { >
offset: [0, -8], <Tooltip
}, title={pagespeedStatusMsg[determineState(monitor)]}
}, disableInteractive
], slotProps={{
}, popper: {
}} modifiers: [
> {
<Box> name: "offset",
<PulseDot color={statusColor[determineState(monitor)]} /> options: {
</Box> offset: [0, -8],
</Tooltip> },
<Typography component="h2" variant="h2"> },
{monitor.url?.replace(/^https?:\/\//, "") || "..."} ],
</Typography> },
<Typography }}
position="relative" >
variant="body2" <Box>
ml={theme.spacing(6)} <PulseDot color={statusColor[determineState(monitor)]} />
mt={theme.spacing(1)} </Box>
sx={{ </Tooltip>
"&:before": { <Typography
position: "absolute", component="h2"
content: `""`, variant="h2"
width: 4, >
height: 4, {monitor.url?.replace(/^https?:\/\//, "") || "..."}
borderRadius: "50%", </Typography>
backgroundColor: theme.palette.text.tertiary, <Typography
opacity: 0.8, position="relative"
left: -10, variant="body2"
top: "50%", ml={theme.spacing(6)}
transform: "translateY(-50%)", mt={theme.spacing(1)}
}, sx={{
}} "&:before": {
> position: "absolute",
Editing... content: `""`,
</Typography> width: 4,
</Stack> height: 4,
</Box> borderRadius: "50%",
<Box alignSelf="flex-end" ml="auto"> backgroundColor: theme.palette.text.tertiary,
<LoadingButton opacity: 0.8,
onClick={handlePause} left: -10,
loading={isLoading} top: "50%",
variant="contained" transform: "translateY(-50%)",
color="secondary" },
sx={{ }}
pl: theme.spacing(4), >
pr: theme.spacing(6), Editing...
"& svg": { </Typography>
mr: theme.spacing(2), </Stack>
"& path": { </Box>
stroke: theme.palette.other.icon, <Box
strokeWidth: 0.1, alignSelf="flex-end"
}, ml="auto"
}, >
}} <LoadingButton
> onClick={handlePause}
{monitor?.isActive ? ( loading={isLoading}
<> variant="contained"
<PauseCircleOutlineIcon /> color="secondary"
Pause sx={{
</> pl: theme.spacing(4),
) : ( pr: theme.spacing(6),
<> "& svg": {
<PlayCircleOutlineRoundedIcon /> mr: theme.spacing(2),
Resume "& path": {
</> stroke: theme.palette.other.icon,
)} strokeWidth: 0.1,
</LoadingButton> },
<LoadingButton },
loading={isLoading} }}
variant="contained" >
color="error" {monitor?.isActive ? (
onClick={() => setIsOpen(true)} <>
sx={{ <PauseCircleOutlineIcon />
ml: theme.spacing(6), Pause
}} </>
> ) : (
Remove <>
</LoadingButton> <PlayCircleOutlineRoundedIcon />
</Box> Resume
</Stack> </>
<ConfigBox> )}
<Box> </LoadingButton>
<Typography component="h2">General settings</Typography> <LoadingButton
<Typography component="p"> loading={isLoading}
Here you can select the URL of the host, together with the variant="contained"
type of monitor. color="error"
</Typography> onClick={() => setIsOpen(true)}
</Box> sx={{
<Stack ml: theme.spacing(6),
gap={theme.spacing(20)} }}
sx={{ >
".MuiInputBase-root:has(> .Mui-disabled)": { Remove
backgroundColor: theme.palette.background.accent, </LoadingButton>
}, </Box>
}} </Stack>
> <ConfigBox>
<Field <Box>
type="url" <Typography component="h2">General settings</Typography>
id="monitor-url" <Typography component="p">
label="URL" Here you can select the URL of the host, together with the type of
placeholder="random.website.com" monitor.
value={monitor?.url?.replace("http://", "") || ""} </Typography>
onChange={handleChange} </Box>
error={errors.url} <Stack
disabled={true} gap={theme.spacing(20)}
/> sx={{
<Field ".MuiInputBase-root:has(> .Mui-disabled)": {
type="text" backgroundColor: theme.palette.background.accent,
id="monitor-name" },
label="Monitor display name" }}
placeholder="Example monitor" >
isOptional={true} <Field
value={monitor?.name || ""} type="url"
onChange={handleChange} id="monitor-url"
error={errors.name} label="URL"
/> placeholder="random.website.com"
</Stack> value={monitor?.url?.replace("http://", "") || ""}
</ConfigBox> onChange={handleChange}
<ConfigBox> error={errors.url}
<Box> disabled={true}
<Typography component="h2">Incident notifications</Typography> />
<Typography component="p"> <Field
When there is an incident, notify users. type="text"
</Typography> id="monitor-name"
</Box> label="Monitor display name"
<Stack gap={theme.spacing(6)}> placeholder="Example monitor"
<Typography component="p"> isOptional={true}
When there is a new incident, value={monitor?.name || ""}
</Typography> onChange={handleChange}
<Checkbox error={errors.name}
id="notify-sms" />
label="Notify via SMS (coming soon)" </Stack>
isChecked={false} </ConfigBox>
value="" <ConfigBox>
onChange={() => logger.warn("disabled")} <Box>
isDisabled={true} <Typography component="h2">Incident notifications</Typography>
/> <Typography component="p">
<Checkbox When there is an incident, notify users.
id="notify-email-default" </Typography>
label={`Notify via email (to ${user.email})`} </Box>
isChecked={ <Stack gap={theme.spacing(6)}>
monitor?.notifications?.some( <Typography component="p">When there is a new incident,</Typography>
(notification) => notification.type === "email" <Checkbox
) || false id="notify-sms"
} label="Notify via SMS (coming soon)"
value={user?.email} isChecked={false}
onChange={(event) => handleChange(event)} value=""
/> onChange={() => logger.warn("disabled")}
<Checkbox isDisabled={true}
id="notify-email" />
label="Also notify via email to multiple addresses (coming soon)" <Checkbox
isChecked={false} id="notify-email-default"
value="" label={`Notify via email (to ${user.email})`}
onChange={() => logger.warn("disabled")} isChecked={
isDisabled={true} monitor?.notifications?.some(
/> (notification) => notification.type === "email"
{monitor?.notifications?.some( ) || false
(notification) => notification.type === "emails" }
) ? ( value={user?.email}
<Box mx={theme.spacing(16)}> onChange={(event) => handleChange(event)}
<Field />
id="notify-email-list" <Checkbox
type="text" id="notify-email"
placeholder="name@gmail.com" label="Also notify via email to multiple addresses (coming soon)"
value="" isChecked={false}
onChange={() => logger.warn("disabled")} value=""
/> onChange={() => logger.warn("disabled")}
<Typography mt={theme.spacing(4)}> isDisabled={true}
You can separate multiple emails with a comma />
</Typography> {monitor?.notifications?.some(
</Box> (notification) => notification.type === "emails"
) : ( ) ? (
"" <Box mx={theme.spacing(16)}>
)} <Field
</Stack> id="notify-email-list"
</ConfigBox> type="text"
<ConfigBox> placeholder="name@gmail.com"
<Box> value=""
<Typography component="h2">Advanced settings</Typography> onChange={() => logger.warn("disabled")}
</Box> />
<Stack gap={theme.spacing(20)}> <Typography mt={theme.spacing(4)}>
<Select You can separate multiple emails with a comma
id="monitor-frequency" </Typography>
label="Check frequency" </Box>
items={frequencies} ) : (
value={monitor?.interval / MS_PER_MINUTE || 3} ""
onChange={(event) => handleChange(event, "interval")} )}
/> </Stack>
</Stack> </ConfigBox>
</ConfigBox> <ConfigBox>
<Stack direction="row" justifyContent="flex-end" mt="auto"> <Box>
<LoadingButton <Typography component="h2">Advanced settings</Typography>
loading={isLoading} </Box>
type="submit" <Stack gap={theme.spacing(20)}>
variant="contained" <Select
color="primary" id="monitor-frequency"
onClick={handleSave} label="Check frequency"
sx={{ px: theme.spacing(12) }} items={frequencies}
> value={monitor?.interval / MS_PER_MINUTE || 3}
Save onChange={(event) => handleChange(event, "interval")}
</LoadingButton> />
</Stack> </Stack>
</Stack> </ConfigBox>
</> <Stack
)} direction="row"
<Modal justifyContent="flex-end"
aria-labelledby="modal-delete-pagespeed-monitor" mt="auto"
aria-describedby="delete-pagespeed-monitor-confirmation" >
open={isOpen} <LoadingButton
onClose={() => setIsOpen(false)} loading={isLoading}
disablePortal type="submit"
> variant="contained"
<Stack color="primary"
gap={theme.spacing(2)} onClick={handleSave}
sx={{ sx={{ px: theme.spacing(12) }}
position: "absolute", >
top: "50%", Save
left: "50%", </LoadingButton>
transform: "translate(-50%, -50%)", </Stack>
width: 400, </Stack>
bgcolor: theme.palette.background.main, </>
border: 1, )}
borderColor: theme.palette.border.light, <Modal
borderRadius: theme.shape.borderRadius, aria-labelledby="modal-delete-pagespeed-monitor"
boxShadow: 24, aria-describedby="delete-pagespeed-monitor-confirmation"
p: theme.spacing(15), open={isOpen}
"&:focus": { onClose={() => setIsOpen(false)}
outline: "none", disablePortal
}, >
}} <Stack
> gap={theme.spacing(2)}
<Typography sx={{
id="modal-delete-pagespeed-monitor" position: "absolute",
component="h2" top: "50%",
variant="h2" left: "50%",
fontWeight={500} transform: "translate(-50%, -50%)",
> width: 400,
Do you really want to delete this monitor? bgcolor: theme.palette.background.main,
</Typography> border: 1,
<Typography borderColor: theme.palette.border.light,
id="delete-pagespeed-monitor-confirmation" borderRadius: theme.shape.borderRadius,
variant="body1" boxShadow: 24,
> p: theme.spacing(15),
Once deleted, this monitor cannot be retrieved. "&:focus": {
</Typography> outline: "none",
<Stack },
direction="row" }}
gap={theme.spacing(4)} >
mt={theme.spacing(12)} <Typography
justifyContent="flex-end" id="modal-delete-pagespeed-monitor"
> component="h2"
<Button variant="h2"
variant="text" fontWeight={500}
color="info" >
onClick={() => setIsOpen(false)} Do you really want to delete this monitor?
> </Typography>
Cancel <Typography
</Button> id="delete-pagespeed-monitor-confirmation"
<Button variant="contained" color="error" onClick={handleRemove}> variant="body1"
Delete >
</Button> Once deleted, this monitor cannot be retrieved.
</Stack> </Typography>
</Stack> <Stack
</Modal> direction="row"
</Stack> gap={theme.spacing(4)}
); mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={() => setIsOpen(false)}
>
Cancel
</Button>
<Button
variant="contained"
color="error"
onClick={handleRemove}
>
Delete
</Button>
</Stack>
</Stack>
</Modal>
</Stack>
);
}; };
export default PageSpeedConfigure; export default PageSpeedConfigure;
@@ -7,45 +7,80 @@ import { useTheme } from "@emotion/react";
* @returns {JSX.Element} * @returns {JSX.Element}
*/ */
const SkeletonLayout = () => { const SkeletonLayout = () => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<> <>
<Skeleton variant="rounded" width="15%" height={34} /> <Skeleton
<Stack gap={theme.spacing(20)} mt={theme.spacing(6)} maxWidth="1000px"> variant="rounded"
<Stack direction="row" gap={theme.spacing(4)} mt={theme.spacing(4)}> width="15%"
<Skeleton height={34}
variant="circular" />
style={{ minWidth: 24, minHeight: 24 }} <Stack
/> gap={theme.spacing(20)}
<Box width="80%"> mt={theme.spacing(6)}
<Skeleton maxWidth="1000px"
variant="rounded" >
width="50%" <Stack
height={24} direction="row"
sx={{ mb: theme.spacing(4) }} gap={theme.spacing(4)}
/> mt={theme.spacing(4)}
<Skeleton variant="rounded" width="50%" height={18} /> >
</Box> <Skeleton
<Stack variant="circular"
direction="row" style={{ minWidth: 24, minHeight: 24 }}
gap={theme.spacing(6)} />
sx={{ <Box width="80%">
ml: "auto", <Skeleton
alignSelf: "flex-end", variant="rounded"
}} width="50%"
> height={24}
<Skeleton variant="rounded" width={100} height={34} /> sx={{ mb: theme.spacing(4) }}
<Skeleton variant="rounded" width={100} height={34} /> />
</Stack> <Skeleton
</Stack> variant="rounded"
<Skeleton variant="rounded" width="100%" height={500} /> width="50%"
<Stack direction="row" justifyContent="flex-end"> height={18}
<Skeleton variant="rounded" width="15%" height={34} /> />
</Stack> </Box>
</Stack> <Stack
</> direction="row"
); gap={theme.spacing(6)}
sx={{
ml: "auto",
alignSelf: "flex-end",
}}
>
<Skeleton
variant="rounded"
width={100}
height={34}
/>
<Skeleton
variant="rounded"
width={100}
height={34}
/>
</Stack>
</Stack>
<Skeleton
variant="rounded"
width="100%"
height={500}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Skeleton
variant="rounded"
width="15%"
height={34}
/>
</Stack>
</Stack>
</>
);
}; };
export default SkeletonLayout; export default SkeletonLayout;
@@ -25,86 +25,86 @@ const CreatePageSpeed = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const theme = useTheme(); const theme = useTheme();
const idMap = { const idMap = {
"monitor-url": "url", "monitor-url": "url",
"monitor-name": "name", "monitor-name": "name",
"monitor-checks-http": "type", "monitor-checks-http": "type",
"monitor-checks-ping": "type", "monitor-checks-ping": "type",
"notify-email-default": "notification-email", "notify-email-default": "notification-email",
}; };
const [monitor, setMonitor] = useState({ const [monitor, setMonitor] = useState({
url: "", url: "",
name: "", name: "",
type: "pagespeed", type: "pagespeed",
notifications: [], notifications: [],
interval: 3, interval: 3,
}); });
const [https, setHttps] = useState(true); const [https, setHttps] = useState(true);
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const handleChange = (event, name) => { const handleChange = (event, name) => {
const { value, id } = event.target; const { value, id } = event.target;
if (!name) name = idMap[id]; if (!name) name = idMap[id];
if (name.includes("notification-")) { if (name.includes("notification-")) {
name = name.replace("notification-", ""); name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some( let hasNotif = monitor.notifications.some(
(notification) => notification.type === name (notification) => notification.type === name
); );
setMonitor((prev) => { setMonitor((prev) => {
const notifs = [...prev.notifications]; const notifs = [...prev.notifications];
if (hasNotif) { if (hasNotif) {
return { return {
...prev, ...prev,
notifications: notifs.filter((notif) => notif.type !== name), notifications: notifs.filter((notif) => notif.type !== name),
}; };
} else { } else {
return { return {
...prev, ...prev,
notifications: [ notifications: [
...notifs, ...notifs,
name === "email" name === "email"
? { type: name, address: value } ? { type: name, address: value }
: // TODO - phone number : // TODO - phone number
{ type: name, phone: value }, { type: name, phone: value },
], ],
}; };
} }
}); });
} else { } else {
setMonitor((prev) => ({ setMonitor((prev) => ({
...prev, ...prev,
[name]: value, [name]: value,
})); }));
const { error } = monitorValidation.validate( const { error } = monitorValidation.validate(
{ [name]: value }, { [name]: value },
{ abortEarly: false } { abortEarly: false }
); );
setErrors((prev) => { setErrors((prev) => {
const updatedErrors = { ...prev }; const updatedErrors = { ...prev };
if (error) updatedErrors[name] = error.details[0].message; if (error) updatedErrors[name] = error.details[0].message;
else delete updatedErrors[name]; else delete updatedErrors[name];
return updatedErrors; return updatedErrors;
}); });
} }
}; };
const handleCreateMonitor = async (event) => { const handleCreateMonitor = async (event) => {
event.preventDefault(); event.preventDefault();
//obj to submit //obj to submit
let form = { let form = {
url: `http${https ? "s" : ""}://` + monitor.url, url: `http${https ? "s" : ""}://` + monitor.url,
name: monitor.name === "" ? monitor.url : monitor.name, name: monitor.name === "" ? monitor.url : monitor.name,
type: monitor.type, type: monitor.type,
interval: monitor.interval * MS_PER_MINUTE, interval: monitor.interval * MS_PER_MINUTE,
}; };
const { error } = monitorValidation.validate(form, { const { error } = monitorValidation.validate(form, {
abortEarly: false, abortEarly: false,
}); });
if (error) { if (error) {
const newErrors = {}; const newErrors = {};
@@ -1,12 +1,12 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { import {
AreaChart, AreaChart,
Area, Area,
XAxis, XAxis,
Tooltip, Tooltip,
CartesianGrid, CartesianGrid,
ResponsiveContainer, ResponsiveContainer,
Text, Text,
} from "recharts"; } from "recharts";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
@@ -15,26 +15,26 @@ import { formatDateWithTz } from "../../../../Utils/timeUtils";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
const config = { const config = {
seo: { seo: {
id: "seo", id: "seo",
text: "SEO", text: "SEO",
color: "unresolved", color: "unresolved",
}, },
performance: { performance: {
id: "performance", id: "performance",
text: "performance", text: "performance",
color: "success", color: "success",
}, },
bestPractices: { bestPractices: {
id: "bestPractices", id: "bestPractices",
text: "best practices", text: "best practices",
color: "warning", color: "warning",
}, },
accessibility: { accessibility: {
id: "accessibility", id: "accessibility",
text: "accessibility", text: "accessibility",
color: "primary", color: "primary",
}, },
}; };
/** /**
@@ -47,81 +47,79 @@ const config = {
*/ */
const CustomToolTip = ({ active, payload, label, config }) => { const CustomToolTip = ({ active, payload, label, config }) => {
const theme = useTheme(); const theme = useTheme();
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
if (active && payload && payload.length) { if (active && payload && payload.length) {
return ( return (
<Box <Box
sx={{ sx={{
backgroundColor: theme.palette.background.main, backgroundColor: theme.palette.background.main,
border: 1, border: 1,
borderColor: theme.palette.border.dark, borderColor: theme.palette.border.dark,
borderRadius: theme.shape.borderRadius, borderRadius: theme.shape.borderRadius,
py: theme.spacing(2), py: theme.spacing(2),
px: theme.spacing(4), px: theme.spacing(4),
}} }}
> >
<Typography <Typography
sx={{ sx={{
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
fontSize: 12, fontSize: 12,
fontWeight: 500, fontWeight: 500,
}} }}
> >
{formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)} {formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)}
</Typography> </Typography>
{Object.keys(config) {Object.keys(config)
.reverse() .reverse()
.map((key) => { .map((key) => {
const { color } = config[key]; const { color } = config[key];
const dotColor = theme.palette[color].main; const dotColor = theme.palette[color].main;
return ( return (
<Stack <Stack
key={`${key}-tooltip`} key={`${key}-tooltip`}
direction="row" direction="row"
alignItems="center" alignItems="center"
gap={theme.spacing(3)} gap={theme.spacing(3)}
mt={theme.spacing(1)} mt={theme.spacing(1)}
sx={{ sx={{
"& span": { "& span": {
color: theme.palette.text.tertiary, color: theme.palette.text.tertiary,
fontSize: 11, fontSize: 11,
fontWeight: 500, fontWeight: 500,
}, },
}} }}
> >
<Box <Box
width={theme.spacing(4)} width={theme.spacing(4)}
height={theme.spacing(4)} height={theme.spacing(4)}
backgroundColor={dotColor} backgroundColor={dotColor}
sx={{ borderRadius: "50%" }} sx={{ borderRadius: "50%" }}
/> />
<Typography <Typography
component="span" component="span"
textTransform="capitalize" textTransform="capitalize"
sx={{ opacity: 0.8 }} sx={{ opacity: 0.8 }}
> >
{config[key].text} {config[key].text}
</Typography>{" "} </Typography>{" "}
<Typography component="span"> <Typography component="span">{payload[0].payload[key]}</Typography>
{payload[0].payload[key]} </Stack>
</Typography> );
</Stack> })}
); </Box>
})} );
</Box> }
); return null;
}
return null;
}; };
CustomToolTip.propTypes = { CustomToolTip.propTypes = {
active: PropTypes.bool, active: PropTypes.bool,
payload: PropTypes.array, payload: PropTypes.array,
label: PropTypes.string, label: PropTypes.string,
config: PropTypes.object, config: PropTypes.object,
}; };
/** /**
@@ -131,38 +129,38 @@ CustomToolTip.propTypes = {
* @returns {Array} The formatted data with gaps. * @returns {Array} The formatted data with gaps.
*/ */
const processDataWithGaps = (data, interval) => { const processDataWithGaps = (data, interval) => {
if (data.length === 0) return []; if (data.length === 0) return [];
let formattedData = []; let formattedData = [];
let last = new Date(data[0].createdAt).getTime(); let last = new Date(data[0].createdAt).getTime();
// Helper function to add a null entry // Helper function to add a null entry
const addNullEntry = (timestamp) => { const addNullEntry = (timestamp) => {
formattedData.push({ formattedData.push({
accessibility: "N/A", accessibility: "N/A",
bestPractices: "N/A", bestPractices: "N/A",
performance: "N/A", performance: "N/A",
seo: "N/A", seo: "N/A",
createdAt: timestamp, createdAt: timestamp,
}); });
}; };
data.forEach((entry) => { data.forEach((entry) => {
const current = new Date(entry.createdAt).getTime(); const current = new Date(entry.createdAt).getTime();
if (current - last > interval * 2) { if (current - last > interval * 2) {
// Insert null entries for each interval // Insert null entries for each interval
let temp = last + interval; let temp = last + interval;
while (temp < current) { while (temp < current) {
addNullEntry(new Date(temp).toISOString()); addNullEntry(new Date(temp).toISOString());
temp += interval; temp += interval;
} }
} }
formattedData.push(entry); formattedData.push(entry);
last = current; last = current;
}); });
return formattedData; return formattedData;
}; };
/** /**
@@ -177,32 +175,32 @@ const processDataWithGaps = (data, interval) => {
* @returns {JSX.Element|null} The tick element or null if the tick should be hidden. * @returns {JSX.Element|null} The tick element or null if the tick should be hidden.
*/ */
const CustomTick = ({ x, y, payload, index }) => { const CustomTick = ({ x, y, payload, index }) => {
const theme = useTheme(); const theme = useTheme();
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
// Render nothing for the first tick // Render nothing for the first tick
if (index === 0) return null; if (index === 0) return null;
return ( return (
<Text <Text
x={x} x={x}
y={y + 8} y={y + 8}
textAnchor="middle" textAnchor="middle"
fill={theme.palette.text.tertiary} fill={theme.palette.text.tertiary}
fontSize={11} fontSize={11}
fontWeight={400} fontWeight={400}
> >
{formatDateWithTz(payload?.value, "h:mm a", uiTimezone)} {formatDateWithTz(payload?.value, "h:mm a", uiTimezone)}
</Text> </Text>
); );
}; };
CustomTick.propTypes = { CustomTick.propTypes = {
x: PropTypes.number, x: PropTypes.number,
y: PropTypes.number, y: PropTypes.number,
payload: PropTypes.shape({ payload: PropTypes.shape({
value: PropTypes.string.isRequired, value: PropTypes.string.isRequired,
}), }),
index: PropTypes.number, index: PropTypes.number,
}; };
/** /**
@@ -214,102 +212,115 @@ CustomTick.propTypes = {
*/ */
const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => { const PagespeedDetailsAreaChart = ({ data, interval, metrics }) => {
const theme = useTheme(); const theme = useTheme();
const [isHovered, setIsHovered] = useState(false); const [isHovered, setIsHovered] = useState(false);
const memoizedData = useMemo( const memoizedData = useMemo(() => processDataWithGaps(data, interval), [data[0]]);
() => processDataWithGaps(data, interval),
[data[0]]
);
const filteredConfig = Object.keys(config).reduce((result, key) => { const filteredConfig = Object.keys(config).reduce((result, key) => {
if (metrics[key]) { if (metrics[key]) {
result[key] = config[key]; result[key] = config[key];
} }
return result; return result;
}, {}); }, {});
return ( return (
<ResponsiveContainer width="100%" minWidth={25} height={215}> <ResponsiveContainer
<AreaChart width="100%"
width="100%" minWidth={25}
height="100%" height={215}
data={memoizedData} >
margin={{ top: 10 }} <AreaChart
onMouseMove={() => setIsHovered(true)} width="100%"
onMouseLeave={() => setIsHovered(false)} height="100%"
> data={memoizedData}
<CartesianGrid margin={{ top: 10 }}
stroke={theme.palette.border.light} onMouseMove={() => setIsHovered(true)}
strokeWidth={1} onMouseLeave={() => setIsHovered(false)}
strokeOpacity={1} >
fill="transparent" <CartesianGrid
vertical={false} stroke={theme.palette.border.light}
/> strokeWidth={1}
<XAxis strokeOpacity={1}
stroke={theme.palette.border.dark} fill="transparent"
dataKey="createdAt" vertical={false}
tick={<CustomTick />} />
axisLine={false} <XAxis
tickLine={false} stroke={theme.palette.border.dark}
height={18} dataKey="createdAt"
minTickGap={0} tick={<CustomTick />}
interval="equidistantPreserveStart" axisLine={false}
/> tickLine={false}
<Tooltip height={18}
cursor={{ stroke: theme.palette.border.light }} minTickGap={0}
content={<CustomToolTip config={filteredConfig} />} interval="equidistantPreserveStart"
/> />
<defs> <Tooltip
{Object.values(filteredConfig).map(({ id, color }) => { cursor={{ stroke: theme.palette.border.light }}
const startColor = theme.palette[color].main; content={<CustomToolTip config={filteredConfig} />}
const endColor = theme.palette[color].light; />
<defs>
{Object.values(filteredConfig).map(({ id, color }) => {
const startColor = theme.palette[color].main;
const endColor = theme.palette[color].light;
return ( return (
<linearGradient id={id} x1="0" y1="0" x2="0" y2="1" key={id}> <linearGradient
<stop offset="0%" stopColor={startColor} stopOpacity={0.8} /> id={id}
<stop offset="100%" stopColor={endColor} stopOpacity={0} /> x1="0"
</linearGradient> y1="0"
); x2="0"
})} y2="1"
</defs> key={id}
{Object.keys(filteredConfig).map((key) => { >
const { color } = filteredConfig[key]; <stop
const strokeColor = theme.palette[color].main; offset="0%"
const bgColor = theme.palette.background.main; stopColor={startColor}
stopOpacity={0.8}
/>
<stop
offset="100%"
stopColor={endColor}
stopOpacity={0}
/>
</linearGradient>
);
})}
</defs>
{Object.keys(filteredConfig).map((key) => {
const { color } = filteredConfig[key];
const strokeColor = theme.palette[color].main;
const bgColor = theme.palette.background.main;
return ( return (
<Area <Area
connectNulls connectNulls
key={key} key={key}
dataKey={key} dataKey={key}
stackId={1} stackId={1}
stroke={strokeColor} stroke={strokeColor}
strokeWidth={isHovered ? 2.5 : 1.5} strokeWidth={isHovered ? 2.5 : 1.5}
fill={`url(#${filteredConfig[key].id})`} fill={`url(#${filteredConfig[key].id})`}
activeDot={{ stroke: bgColor, fill: strokeColor, r: 4.5 }} activeDot={{ stroke: bgColor, fill: strokeColor, r: 4.5 }}
/> />
); );
})} })}
</AreaChart> </AreaChart>
</ResponsiveContainer> </ResponsiveContainer>
); );
}; };
PagespeedDetailsAreaChart.propTypes = { PagespeedDetailsAreaChart.propTypes = {
data: PropTypes.arrayOf( data: PropTypes.arrayOf(
PropTypes.shape({ PropTypes.shape({
createdAt: PropTypes.string.isRequired, createdAt: PropTypes.string.isRequired,
accessibility: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) accessibility: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
.isRequired, bestPractices: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
bestPractices: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) performance: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
.isRequired, seo: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
performance: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) })
.isRequired, ).isRequired,
seo: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, interval: PropTypes.number.isRequired,
}) metrics: PropTypes.object,
).isRequired,
interval: PropTypes.number.isRequired,
metrics: PropTypes.object,
}; };
export default PagespeedDetailsAreaChart; export default PagespeedDetailsAreaChart;
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more