Merge pull request #1091 from bluewave-labs/develop

Develop -> Master
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-10-30 09:59:35 +08:00
commit 79d0f00826
254 files changed
+46378 -40799

No files matched your search

@@ -1,9 +1,14 @@
## Describe your changes ## Describe your changes
## Issue Number if applicable Provide a brief description of the changes you’ve made and their purpose.
## Checklist before requesting a review ## Issue number
- [ ] I have performed a self-review of my code Mention the issue number(s) this PR addresses (e.g., #123).
- [ ] I have inlcuded the issue # in the PR if applicable
- [ ] I have labelled the PR correctly ## Please ensure all items are checked off before requesting a review:
- [ ] I have performed a self-review of my code.
- [ ] I have included the issue # in the PR.
- [ ] I have labelled the PR correctly.
- [ ] My PR is granular and targeted to one specific feature only.
+16
View File
@@ -0,0 +1,16 @@
{
"printWidth": 90,
"useTabs": true,
"tabWidth": 2,
"singleQuote": false,
"bracketSpacing": true,
"proseWrap": "preserve",
"bracketSameLine": false,
"singleAttributePerLine": true,
"semi": true,
"jsxSingleQuote": false,
"quoteProps": "as-needed",
"arrowParens": "always",
"trailingComma": "es5",
"htmlWhitespaceSensitivity": "css"
}
+69
View File
@@ -0,0 +1,69 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in the **bluewave-uptime** project and community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community, especially during Hacktoberfest, where we encourage new contributors to join and feel supported.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned with this Code of Conduct, especially during Hacktoberfest to ensure a positive experience for all contributors.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when an individual is officially representing the project or its community in public spaces. Examples of representing our project include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hello@bluewavelabs.ca. All complaints will be reviewed and investigated promptly and fairly.
All project team members are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Project maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from project maintainers, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
---
By following this Code of Conduct, we can ensure a welcoming and inclusive environment, encouraging new contributors to engage with the project and the community. Thank you for helping make **bluewave-uptime** a positive space for all!
+1
View File
@@ -77,6 +77,7 @@ Once it's filed:
This section guides you through submitting an enhancement suggestion for the application, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community understand your enhancements and find related suggestions. This section guides you through submitting an enhancement suggestion for the application, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community understand your enhancements and find related suggestions.
- Make sure that you are using the latest version. - Make sure that you are using the latest version.
- Make sure you run the code locally. The Uptime Manager [documentation](https://bluewavelabs.gitbook.io/uptime-manager) covers it.
- Find out if the functionality is already covered, maybe by an individual configuration. - Find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search](/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. - Perform a [search](/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library. - Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. If you're just targeting a minority of users, consider writing an add-on/plugin library.
+1
View File
@@ -0,0 +1 @@
VITE_APP_API_BASE_URL=UPTIME_APP_API_BASE_URL
+18 -20
View File
@@ -1,21 +1,19 @@
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', "react/no-unescaped-entities": "off",
{ allowConstantExport: true }, },
], };
},
}
+2
View File
@@ -24,3 +24,5 @@ dist-ssr
*.sw? *.sw?
.env .env
!env.sh
Executable
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
for i in $(env | grep UPTIME_APP_)
do
key=$(echo $i | cut -d '=' -f 1)
value=$(echo $i | cut -d '=' -f 2-)
echo $key=$value
find /usr/share/nginx/html -type f \( -name '*.js' -o -name '*.css' \) -exec sed -i "s|${key}|${value}|g" '{}' +
done
+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>
+6493 -6484
View File
File diff suppressed because it is too large. Load diff
+48 -46
View File
@@ -1,48 +1,50 @@
{ {
"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", "build-dev": "vite build --mode development",
"preview": "vite preview" "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
}, "preview": "vite preview"
"dependencies": { },
"@emotion/react": "^11.11.4", "dependencies": {
"@emotion/styled": "^11.11.5", "@emotion/react": "^11.11.4",
"@fontsource/roboto": "^5.0.13", "@emotion/styled": "^11.11.5",
"@mui/icons-material": "^5.15.17", "@fontsource/roboto": "^5.0.13",
"@mui/lab": "^5.0.0-alpha.170", "@mui/icons-material": "^5.15.17",
"@mui/material": "^5.15.16", "@mui/lab": "^5.0.0-alpha.170",
"@mui/x-charts": "^7.5.1", "@mui/material": "^5.15.16",
"@mui/x-data-grid": "7.3.2", "@mui/x-charts": "^7.5.1",
"@mui/x-date-pickers": "7.3.2", "@mui/x-data-grid": "7.22.0",
"@reduxjs/toolkit": "2.2.5", "@mui/x-date-pickers": "7.22.0",
"axios": "^1.7.4", "@reduxjs/toolkit": "2.3.0",
"chart.js": "^4.4.3", "axios": "^1.7.4",
"dayjs": "1.11.11", "chart.js": "^4.4.3",
"joi": "17.13.1", "dayjs": "1.11.13",
"jwt-decode": "^4.0.0", "joi": "17.13.3",
"react": "^18.2.0", "jwt-decode": "^4.0.0",
"react-dom": "^18.2.0", "react": "^18.2.0",
"react-redux": "9.1.2", "react-dom": "^18.2.0",
"react-router": "^6.23.0", "react-redux": "9.1.2",
"react-router-dom": "^6.23.1", "react-router": "^6.23.0",
"react-toastify": "^10.0.5", "react-router-dom": "^6.23.1",
"recharts": "2.13.0-alpha.4", "react-toastify": "^10.0.5",
"redux-persist": "6.0.0", "recharts": "2.13.1",
"vite-plugin-svgr": "^4.2.0" "redux-persist": "6.0.0",
}, "vite-plugin-svgr": "^4.2.0"
"devDependencies": { },
"@types/react": "^18.2.66", "devDependencies": {
"@types/react-dom": "^18.2.22", "@types/react": "^18.2.66",
"@vitejs/plugin-react": "^4.2.1", "@types/react-dom": "^18.2.22",
"eslint": "^8.57.0", "@vitejs/plugin-react": "^4.2.1",
"eslint-plugin-react": "^7.34.1", "eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-refresh": "^0.4.6", "eslint-plugin-react-hooks": "^5.0.0",
"vite": "^5.2.0" "eslint-plugin-react-refresh": "^0.4.6",
} "prettier": "^3.3.3",
"vite": "^5.2.0"
}
} }
+2 -2
View File
@@ -1,7 +1,7 @@
.card { .card {
padding: 2em; padding: 2em;
} }
.read-the-docs { .read-the-docs {
color: #888; color: #888;
} }
+166 -127
View File
@@ -36,142 +36,181 @@ import { useSelector } from "react-redux";
import { CssBaseline } from "@mui/material"; import { CssBaseline } from "@mui/material";
import { useEffect } from "react"; import { useEffect } from "react";
import { useDispatch } from "react-redux"; import { useDispatch } from "react-redux";
import { getAppSettings } from "./Features/Settings/settingsSlice"; import { getAppSettings, updateAppSettings } 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 exact path="/" element={<HomeLayout />}> <Route
<Route exact
exact path="/"
path="/" element={<HomeLayout />}
element={<ProtectedRoute Component={MonitorsWithAdminProp} />} >
/> <Route
<Route exact
path="/monitors" path="/"
element={<ProtectedRoute Component={MonitorsWithAdminProp} />} element={<ProtectedRoute Component={MonitorsWithAdminProp} />}
/> />
<Route <Route
path="/monitors/create/:monitorId?" path="/monitors"
element={<ProtectedRoute Component={CreateMonitor} />} element={<ProtectedRoute Component={MonitorsWithAdminProp} />}
/> />
<Route <Route
path="/monitors/:monitorId/" path="/monitors/create/:monitorId?"
element={<ProtectedRoute Component={MonitorDetailsWithAdminProp} />} element={<ProtectedRoute Component={CreateMonitor} />}
/> />
<Route <Route
path="/monitors/configure/:monitorId/" path="/monitors/:monitorId/"
element={<ProtectedRoute Component={Configure} />} element={<ProtectedRoute Component={MonitorDetailsWithAdminProp} />}
/> />
<Route <Route
path="incidents/:monitorId?" path="/monitors/configure/:monitorId/"
element={<ProtectedRoute Component={Incidents} />} element={<ProtectedRoute Component={Configure} />}
/> />
<Route
path="incidents/:monitorId?"
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={ element={<ProtectedRoute Component={AdvancedSettingsWithAdminProp} />}
<ProtectedRoute Component={AdvancedSettingsWithAdminProp} /> />
} <Route
/> path="account/profile"
<Route element={
path="account/profile" <ProtectedRoute
element={<ProtectedRoute Component={Account} open="profile" />} Component={Account}
/> open="profile"
<Route />
path="account/password" }
element={<ProtectedRoute Component={Account} open="password" />} />
/> <Route
<Route path="account/password"
path="account/team" element={
element={<ProtectedRoute Component={Account} open="team" />} <ProtectedRoute
/> Component={Account}
<Route open="password"
path="pagespeed" />
element={<ProtectedRoute Component={PageSpeedWithAdminProp} />} }
/> />
<Route <Route
path="pagespeed/create" path="account/team"
element={<ProtectedRoute Component={CreatePageSpeed} />} element={
/> <ProtectedRoute
<Route Component={Account}
path="pagespeed/:monitorId" open="team"
element={ />
<ProtectedRoute Component={PageSpeedDetailsWithAdminProp} /> }
} />
/> <Route
<Route path="pagespeed"
path="pagespeed/configure/:monitorId" element={<ProtectedRoute Component={PageSpeedWithAdminProp} />}
element={<ProtectedRoute Component={PageSpeedConfigure} />} />
/> <Route
</Route> path="pagespeed/create"
element={<ProtectedRoute Component={CreatePageSpeed} />}
/>
<Route
path="pagespeed/:monitorId"
element={<ProtectedRoute Component={PageSpeedDetailsWithAdminProp} />}
/>
<Route
path="pagespeed/configure/:monitorId"
element={<ProtectedRoute Component={PageSpeedConfigure} />}
/>
</Route>
<Route exact path="/login" element={<Login />} /> <Route
exact
path="/login"
element={<Login />}
/>
<Route exact path="/register" element={<AdminCheckedRegister />} /> <Route
<Route exact path="/register/:token" element={<Register />} /> exact
{/* <Route path="/toast" element={<ToastComponent />} /> */} path="/register"
<Route path="*" element={<NotFound />} /> element={<AdminCheckedRegister />}
<Route path="/forgot-password" element={<ForgotPassword />} /> />
<Route path="/check-email" element={<CheckEmail />} /> <Route
<Route path="/set-new-password/:token" element={<SetNewPassword />} /> exact
<Route path="/register/:token"
path="/new-password-confirmed" element={<Register />}
element={<NewPasswordConfirmed />} />
/> {/* <Route path="/toast" element={<ToastComponent />} /> */}
</Routes> <Route
<ToastContainer /> path="*"
</ThemeProvider> element={<NotFound />}
); />
<Route
path="/forgot-password"
element={<ForgotPassword />}
/>
<Route
path="/check-email"
element={<CheckEmail />}
/>
<Route
path="/set-new-password/:token"
element={<SetNewPassword />}
/>
<Route
path="/new-password-confirmed"
element={<NewPasswordConfirmed />}
/>
</Routes>
<ToastContainer />
</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;
+63 -66
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;
} }
.monitors .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 @@
@@ -0,0 +1,68 @@
import { useId } from "react";
import PropTypes from "prop-types";
import { Modal, Stack, Typography } from "@mui/material";
const GenericDialog = ({ title, description, open, onClose, theme, children }) => {
const titleId = useId();
const descriptionId = useId();
const ariaDescribedBy = description?.length > 0 ? descriptionId : "";
return (
<Modal
aria-labelledby={titleId}
aria-describedby={ariaDescribedBy}
open={open}
onClose={onClose}
onClick={(e)=>e.stopPropagation()}
>
<Stack
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id={titleId}
component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}
>
{title}
</Typography>
{description && (
<Typography
id={descriptionId}
color={theme.palette.text.tertiary}
>
{description}
</Typography>
)}
{children}
</Stack>
</Modal>
);
};
GenericDialog.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string,
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
export { GenericDialog };
+62
View File
@@ -0,0 +1,62 @@
import PropTypes from "prop-types";
import LoadingButton from "@mui/lab/LoadingButton";
import { Button, Stack } from "@mui/material";
import { GenericDialog } from "./genericDialog";
const Dialog = ({
title,
description,
open,
theme,
onCancel,
confirmationButtonLabel,
onConfirm,
isLoading,
}) => {
return (
<GenericDialog
title={title}
description={description}
open={open}
onClose={onCancel}
theme={theme}
>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={onCancel}
>
Cancel
</Button>
<LoadingButton
variant="contained"
color="error"
loading={isLoading}
onClick={onConfirm}
>
{confirmationButtonLabel}
</LoadingButton>
</Stack>
</GenericDialog>
);
};
Dialog.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string,
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired,
onCancel: PropTypes.func.isRequired,
confirmationButtonLabel: PropTypes.string.isRequired,
onConfirm: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
};
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);
} }
+190 -201
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,207 +27,202 @@ 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, onBlur,
error, onInput,
disabled, error,
hidden, disabled,
}, 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" : "",
> }}
{label && ( >
<Typography {label && (
component="h3" <Typography
color={theme.palette.text.secondary} component="h3"
fontWeight={500} color={theme.palette.text.secondary}
> fontWeight={500}
{label} >
{isRequired ? ( {label}
<Typography {isRequired ? (
component="span" <Typography
ml={theme.spacing(1)} component="span"
color={theme.palette.error.text} ml={theme.spacing(1)}
> color={theme.palette.error.text}
* >
</Typography> *
) : ( </Typography>
"" ) : (
)} ""
{isOptional ? ( )}
<Typography {isOptional ? (
component="span" <Typography
fontSize="inherit" component="span"
fontWeight={400} fontSize="inherit"
ml={theme.spacing(2)} fontWeight={400}
sx={{ opacity: 0.6 }} ml={theme.spacing(2)}
> sx={{ opacity: 0.6 }}
{optionalLabel || "(optional)"} >
</Typography> {optionalLabel || "(optional)"}
) : ( </Typography>
"" ) : (
)} ""
</Typography> )}
)} </Typography>
<TextField )}
type={type === "password" ? (isVisible ? "text" : type) : type} <TextField
name={name} type={type === "password" ? (isVisible ? "text" : type) : type}
id={id} name={name}
autoComplete={autoComplete} id={id}
placeholder={placeholder} autoComplete={autoComplete}
multiline={type === "description"} placeholder={placeholder}
rows={type === "description" ? 4 : 1} multiline={type === "description"}
value={value} rows={type === "description" ? 4 : 1}
onInput={onInput} value={value}
onChange={onChange} onInput={onInput}
disabled={disabled} onChange={onChange}
inputRef={ref} onBlur={onBlur}
inputProps={{ disabled={disabled}
sx: { inputRef={ref}
color: theme.palette.text.secondary, inputProps={{
"&:-webkit-autofill": { sx: {
WebkitBoxShadow: `0 0 0 100px ${theme.palette.other.autofill} inset`, color: theme.palette.text.secondary,
WebkitTextFillColor: theme.palette.text.secondary, "&:-webkit-autofill": {
borderRadius: "0 5px 5px 0", WebkitBoxShadow: `0 0 0 100px ${theme.palette.other.autofill} inset`,
}, WebkitTextFillColor: theme.palette.text.secondary,
}, borderRadius: "0 5px 5px 0",
}} },
sx={ },
type === "url" }}
? { sx={
"& .MuiInputBase-root": { padding: 0 }, type === "url"
"& .MuiStack-root": { ? {
borderTopLeftRadius: theme.shape.borderRadius, "& .MuiInputBase-root": { padding: 0 },
borderBottomLeftRadius: theme.shape.borderRadius, "& .MuiStack-root": {
}, borderTopLeftRadius: theme.shape.borderRadius,
} borderBottomLeftRadius: theme.shape.borderRadius,
: { },
display: hidden ? "none" : "", }
} : {}
} }
InputProps={{ InputProps={{
startAdornment: type === "url" && ( startAdornment: type === "url" && (
<Stack <Stack
direction="row" direction="row"
alignItems="center" alignItems="center"
height="100%" height="100%"
sx={{ sx={{
borderRight: `solid 1px ${theme.palette.border.dark}`, borderRight: `solid 1px ${theme.palette.border.dark}`,
backgroundColor: theme.palette.background.accent, backgroundColor: theme.palette.background.accent,
pl: theme.spacing(6), pl: theme.spacing(6),
}} }}
> >
<Typography <Typography
component="h5" component="h5"
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
sx={{ lineHeight: 1 }} sx={{ lineHeight: 1 }}
> >
{https ? "https" : "http"}:// {https ? "https" : "http"}://
</Typography> </Typography>
</Stack> </Stack>
), ),
endAdornment: type === "password" && ( endAdornment: type === "password" && (
<InputAdornment position="end"> <InputAdornment position="end">
<IconButton <IconButton
aria-label="toggle password visibility" aria-label="toggle password visibility"
onClick={() => setVisible((show) => !show)} onClick={() => setVisible((show) => !show)}
tabIndex={-1} tabIndex={-1}
sx={{ sx={{
color: theme.palette.border.dark, color: theme.palette.border.dark,
padding: theme.spacing(1), padding: theme.spacing(1),
"&:focus": { "&:focus": {
outline: "none", outline: "none",
}, },
"& .MuiTouchRipple-root": { "& .MuiTouchRipple-root": {
pointerEvents: "none", pointerEvents: "none",
display: "none", display: "none",
}, },
}} }}
> >
{!isVisible ? <VisibilityOff /> : <Visibility />} {!isVisible ? <VisibilityOff /> : <Visibility />}
</IconButton> </IconButton>
</InputAdornment> </InputAdornment>
), ),
}} }}
/> />
{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>
); );
} }
); );
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, onBlur: PropTypes.func,
isOptional: PropTypes.bool, onInput: PropTypes.func,
optionalLabel: PropTypes.string, error: PropTypes.string,
autoComplete: PropTypes.string, disabled: PropTypes.bool,
placeholder: PropTypes.string, hidden: PropTypes.bool,
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;
+158 -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,172 @@ 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>
); );
}; };
//TODO keep search state inside of component
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;
} }
+101 -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,111 @@ import "./index.css";
*/ */
const Select = ({ const Select = ({
id, id,
label, label,
placeholder, placeholder,
isHidden, isHidden,
value, value,
items, items,
onChange, onChange,
sx, onBlur,
name = "", sx,
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} onBlur={onBlur}
MenuProps={{ disableScrollLock: true }} displayEmpty
sx={{ name={name}
fontSize: 13, inputProps={{ id: id }}
minWidth: "125px", IconComponent={KeyboardArrowDownIcon}
"& fieldset": { MenuProps={{ disableScrollLock: true }}
borderRadius: theme.shape.borderRadius, sx={{
borderColor: theme.palette.border.dark, fontSize: 13,
}, minWidth: "125px",
"&:not(.Mui-focused):hover fieldset": { "& fieldset": {
borderColor: theme.palette.border.dark, borderRadius: theme.shape.borderRadius,
}, borderColor: theme.palette.border.dark,
"& svg path": { },
fill: theme.palette.other.icon, "&:not(.Mui-focused):hover fieldset": {
}, borderColor: theme.palette.border.dark,
...sx, },
}} "& svg path": {
> fill: theme.palette.other.icon,
{placeholder && ( },
<MenuItem ...sx,
className="select-placeholder" }}
value="0" >
sx={{ {placeholder && (
display: isHidden ? "none" : "flex", <MenuItem
visibility: isHidden ? "none" : "visible", className="select-placeholder"
...itemStyles, value="0"
}} sx={{
> display: isHidden ? "none" : "flex",
{placeholder} visibility: isHidden ? "none" : "visible",
</MenuItem> ...itemStyles,
)} }}
{items.map((item) => ( >
<MenuItem {placeholder}
value={item._id} </MenuItem>
key={`${id}-${item._id}`} )}
sx={{ {items.map((item) => (
...itemStyles, <MenuItem
}} value={item._id}
> key={`${id}-${item._id}`}
{item.name} sx={{
</MenuItem> ...itemStyles,
))} }}
</MuiSelect> >
</Stack> {item.name}
); </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, onBlur: PropTypes.func,
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;
@@ -1,17 +1,13 @@
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import TabPanel from "@mui/lab/TabPanel"; import TabPanel from "@mui/lab/TabPanel";
import { Box, Button, Divider, Modal, Stack, Typography } from "@mui/material"; import { Box, Button, Divider, Stack, Typography } from "@mui/material";
import Avatar from "../../Avatar"; import Avatar from "../../Avatar";
import Field from "../../Inputs/Field"; 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";
@@ -19,6 +15,8 @@ import { clearUptimeMonitorState } from "../../../Features/UptimeMonitors/uptime
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { GenericDialog } from "../../Dialog/genericDialog";
import Dialog from "../../Dialog";
/** /**
* ProfilePanel component displays a form for editing user profile information * ProfilePanel component displays a form for editing user profile information
@@ -29,479 +27,432 @@ 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">
Really delete this account? <Dialog
</Typography> open={isModalOpen("delete")}
<Typography id="delete-account-confirmation" component="p"> theme={theme}
If you delete your account, you will no longer be able to sign in, title={"Really delete this account?"}
and all of your data will be deleted. Deleting your account is description={
permanent and non-recoverable action. "If you delete your account, you will no longer be able to sign in, and all of your data will be deleted. Deleting your account is permanent and non-recoverable action."
</Typography> }
<Stack onCancel={() => setIsOpen("")}
direction="row" confirmationButtonLabel={"Delete account"}
gap={theme.spacing(5)} onConfirm={handleDeleteAccount}
mt={theme.spacing(5)} isLoading={isLoading}
justifyContent="flex-end" />
>
<Button variant="text" color="info" onClick={() => setIsOpen("")}> <GenericDialog
Cancel title={"Upload Image"}
</Button> open={isModalOpen("picture")}
<LoadingButton onClose={closePictureModal}
variant="contained" theme={theme}
color="error" >
onClick={handleDeleteAccount} <ImageField
loading={isLoading} id="update-profile-picture"
> src={
Delete account file?.delete
</LoadingButton> ? ""
</Stack> : file?.src
</Stack> ? file.src
</Modal> : localData?.file
<Modal ? localData.file
aria-labelledby="modal-update-picture" : user?.avatarImage
aria-describedby="update-profile-picture" ? `data:image/png;base64,${user.avatarImage}`
open={isModalOpen("picture")} : ""
onClose={closePictureModal} }
> loading={progress.isLoading && progress.value !== 100}
<Stack onChange={handlePicture}
sx={{ />
position: "absolute", {progress.isLoading || progress.value !== 0 || errors["picture"] ? (
top: "50%", <ProgressUpload
left: "50%", icon={<ImageIcon />}
transform: "translate(-50%, -50%)", label={file?.name}
width: 475, size={file?.size}
bgcolor: theme.palette.background.main, progress={progress.value}
border: 1, onClick={removePicture}
borderColor: theme.palette.border.light, error={errors["picture"]}
borderRadius: theme.shape.borderRadius, />
boxShadow: theme.shape.boxShadow, ) : (
p: theme.spacing(15), ""
"&:focus": { )}
outline: "none", <Stack
}, direction="row"
}} mt={theme.spacing(10)}
> gap={theme.spacing(5)}
<Typography justifyContent="flex-end"
id="modal-update-picture" >
component="h1" <Button
color={theme.palette.text.secondary} variant="text"
> color="info"
Upload Image onClick={removePicture}
</Typography> >
<ImageField Remove
id="update-profile-picture" </Button>
src={ <Button
file?.delete variant="contained"
? "" color="primary"
: file?.src onClick={handleUpdatePicture}
? file.src disabled={
: localData?.file (Object.keys(errors).length !== 0 && errors?.picture) ||
? localData.file progress.value !== 100
: user?.avatarImage ? true
? `data:image/png;base64,${user.avatarImage}` : false
: "" }
} >
loading={progress.isLoading && progress.value !== 100} Update
onChange={handlePicture} </Button>
/> </Stack>
{progress.isLoading || progress.value !== 0 || errors["picture"] ? ( </GenericDialog>
<ProgressUpload </TabPanel>
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="outlined"
color="secondary"
disabled
sx={{ mr: "auto" }}
>
Edit
</Button>
<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 { Button, ButtonGroup, 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";
@@ -17,6 +10,7 @@ import { useSelector } from "react-redux";
import BasicTable from "../../BasicTable"; import BasicTable from "../../BasicTable";
import Select from "../../Inputs/Select"; import Select from "../../Inputs/Select";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import { GenericDialog } from "../../Dialog/genericDialog";
/** /**
* TeamPanel component manages the organization and team members, * TeamPanel component manages the organization and team members,
@@ -27,207 +21,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 [errors, setErrors] = useState({}); const [isDisabled, setIsDisabled] = useState(true);
const [isSendingInvite, setIsSendingInvite] = useState(false); const [errors, setErrors] = useState({});
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(() => {
setIsDisabled(Object.keys(errors).length !== 0 || 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 () => {
setIsSendingInvite(true); if (!toInvite.email) {
if (!toInvite.role.includes("user") || !toInvite.role.includes("admin")) setErrors((prev) => ({ ...prev, email: "Email is required." }));
setToInvite((prev) => ({ ...prev, role: ["user"] })); return;
}
setIsSendingInvite(true);
if (!toInvite.role.includes("user") || !toInvite.role.includes("admin"))
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
value="team" className="team-panel table-container"
sx={{ value="team"
"& h1": { sx={{
color: theme.palette.text.tertiary, "& h1": {
}, 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 */} >
{/* <Stack component="form"> {/* FEATURE STILL TO BE IMPLEMENTED */}
{/* <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>
@@ -273,161 +271,128 @@ 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}
onClose={closeInviteModal} <GenericDialog
> title={"Invite new team member"}
<Stack description={
gap={theme.spacing(5)} "When you add a new team member, they will get access to all monitors."
sx={{ }
position: "absolute", open={isOpen}
top: "50%", onClose={closeInviteModal}
left: "50%", theme={theme}
transform: "translate(-50%, -50%)", >
width: 450, <Field
bgcolor: theme.palette.background.main, type="email"
border: 1, id="input-team-member"
borderColor: theme.palette.border.light, placeholder="Email"
borderRadius: theme.shape.borderRadius, value={toInvite.email}
boxShadow: theme.shape.boxShadow, onChange={handleChange}
p: theme.spacing(15), error={errors.email}
"&:focus": { />
outline: "none", <Select
}, id="team-member-role"
}} placeholder="Select role"
> isHidden={true}
<Box> value={toInvite.role[0]}
<Typography onChange={(event) =>
id="modal-invite-member" setToInvite((prev) => ({
component="h1" ...prev,
fontWeight={600} role: [event.target.value],
fontColor={theme.palette.text.secondary} }))
> }
Invite new team member items={[
</Typography> { _id: "admin", name: "Admin" },
<Typography { _id: "user", name: "User" },
id="invite-member-to-team" ]}
component="p" />
fontSize={13} <Stack
color={theme.palette.text.accent} direction="row"
sx={{ mt: theme.spacing(1), mb: theme.spacing(4) }} gap={theme.spacing(4)}
> mt={theme.spacing(8)}
When you add a new team member, they will get access to all justifyContent="flex-end"
monitors. >
</Typography> <LoadingButton
</Box> loading={isSendingInvite}
<Field variant="text"
type="email" color="info"
id="input-team-member" onClick={closeInviteModal}
placeholder="Email" >
value={toInvite.email} Cancel
onChange={handleChange} </LoadingButton>
error={errors.email} <LoadingButton
/> variant="contained"
<Select color="primary"
id="team-member-role" onClick={handleInviteMember}
placeholder="Select role" loading={isSendingInvite}
isHidden={true} disabled={isDisabled}
value={toInvite.role[0]} >
onChange={(event) => Send invite
setToInvite((prev) => ({ </LoadingButton>
...prev, </Stack>
role: [event.target.value], </GenericDialog>
})) </TabPanel>
} );
items={[
{ _id: "admin", name: "Admin" },
{ _id: "user", name: "User" },
]}
/>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(8)}
justifyContent="flex-end"
>
<LoadingButton
loading={isSendingInvite}
variant="text"
color="info"
onClick={closeInviteModal}
>
Cancel
</LoadingButton>
<LoadingButton
variant="contained"
color="primary"
onClick={handleInviteMember}
loading={isSendingInvite}
disabled={Object.keys(errors).length !== 0}
>
Send invite
</LoadingButton>
</Stack>
</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,324 @@ 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 checkEndpointResolution = createAsyncThunk(
"monitors/checkEndpoint",
async (data, thunkApi) => {
try {
const { authToken, monitorURL } = data;
const res = await networkService.checkEndpointResolution({
authToken: authToken,
monitorURL: monitorURL,
})
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 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";
}) })
// *****************************************************
// Resolve Endpoint
// *****************************************************
.addCase(checkEndpointResolution.pending, (state) => {
state.isLoading = true;
})
.addCase(checkEndpointResolution.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
})
.addCase(checkEndpointResolution.rejected, (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? action.payload.msg
: "Failed to check endpoint resolution";
})
// *****************************************************
// Update Monitor
// *****************************************************
.addCase(updatePageSpeed.pending, (state) => {
state.isLoading = true;
})
.addCase(updatePageSpeed.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
})
.addCase(updatePageSpeed.rejected, (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? action.payload.msg
: "Failed to update page speed monitor";
})
// ***************************************************** // *****************************************************
// Update Monitor // Delete Monitor
// ***************************************************** // *****************************************************
.addCase(updatePageSpeed.pending, (state) => { .addCase(deletePageSpeed.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(updatePageSpeed.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(updatePageSpeed.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 update page speed monitor"; : "Failed to delete page speed monitor";
}) })
// *****************************************************
// ***************************************************** // Pause Monitor
// Delete Monitor // *****************************************************
// ***************************************************** .addCase(pausePageSpeed.pending, (state) => {
.addCase(deletePageSpeed.pending, (state) => { state.isLoading = true;
state.isLoading = true; })
}) .addCase(pausePageSpeed.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(pausePageSpeed.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 pause page speed monitor";
: "Failed to delete page speed monitor"; });
}) },
// *****************************************************
// Pause Monitor
// *****************************************************
.addCase(pausePageSpeed.pending, (state) => {
state.isLoading = true;
})
.addCase(pausePageSpeed.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
})
.addCase(pausePageSpeed.rejected, (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? action.payload.msg
: "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;
+42 -45
View File
@@ -1,56 +1,53 @@
import { createSlice } from "@reduxjs/toolkit"; import { createSlice } from "@reduxjs/toolkit";
const initialMode = window?.matchMedia?.('(prefers-color-scheme: dark)')?.matches ? "dark" : "light";
// 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: initialMode,
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,405 +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(
"monitors/checkEndpoint",
async (data, thunkApi) => {
try {
const { authToken, monitorURL } = data;
const res = await networkService.checkEndpointResolution({
authToken: authToken,
monitorURL: monitorURL,
})
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 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";
}) })
// ***************************************************** // *****************************************************
// Get Monitor By Id // Resolve Endpoint
// ***************************************************** // *****************************************************
.addCase(getUptimeMonitorById.pending, (state) => { .addCase(checkEndpointResolution.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(getUptimeMonitorById.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(getUptimeMonitorById.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 get uptime monitor"; : "Failed to check endpoint resolution";
}) })
// ***************************************************** // *****************************************************
// update Monitor // Get Monitor By Id
// ***************************************************** // *****************************************************
.addCase(updateUptimeMonitor.pending, (state) => { .addCase(getUptimeMonitorById.pending, (state) => {
state.isLoading = true; state.isLoading = true;
}) })
.addCase(updateUptimeMonitor.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(updateUptimeMonitor.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 update uptime monitor"; // *****************************************************
}) // update Monitor
// *****************************************************
.addCase(updateUptimeMonitor.pending, (state) => {
state.isLoading = true;
})
.addCase(updateUptimeMonitor.fulfilled, (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
})
.addCase(updateUptimeMonitor.rejected, (state, action) => {
state.isLoading = false;
state.success = false;
state.msg = action.payload
? 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;
+319 -236
View File
@@ -9,257 +9,340 @@ 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";
import { advancedSettingsValidation } from "../../Validation/validation";
import { buildErrors, hasValidationErrors } from "../../Validation/error";
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 [errors, setErrors] = useState({});
const theme = useTheme();
const { authToken } = useSelector((state) => state.auth);
const dispatch = useDispatch();
const settings = useSelector((state) => state.settings);
const [localSettings, setLocalSettings] = useState({
apiBaseUrl: "",
logLevel: "debug",
systemEmailHost: "",
systemEmailPort: "",
systemEmailAddress: "",
systemEmailPassword: "",
jwtTTLNum: 99,
jwtTTLUnits: "days",
jwtTTL: "99d",
dbType: "",
redisHost: "",
redisPort: "",
pagespeedApiKey: "",
});
const theme = useTheme(); const parseJWTTTL = (data) => {
const { authToken } = useSelector((state) => state.auth); if (data.jwtTTL) {
const dispatch = useDispatch(); const len = data.jwtTTL.length;
const settings = useSelector((state) => state.settings); data.jwtTTLNum = data.jwtTTL.substring(0, len - 1);
const [localSettings, setLocalSettings] = useState({ data.jwtTTLUnits = unitItems.filter(
apiBaseUrl: "", (itm) => itm._id == data.jwtTTL.substring(len - 1)
logLevel: "debug", )[0].name;
systemEmailHost: "", }
systemEmailPort: "", };
systemEmailAddress: "",
systemEmailPassword: "",
jwtTTL: "",
dbType: "",
redisHost: "",
redisPort: "",
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); parseJWTTTL(action.payload.data);
} else { setLocalSettings(action.payload.data);
createToast({ body: "Failed to get settings" }); } else {
} createToast({ body: "Failed to get settings" });
}; }
getSettings(); };
}, [authToken, dispatch]); getSettings();
}, [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 unitItemLookup = {
const id = e.target.value; days: "d",
const newLogLevel = logItems.find((item) => item._id === id).name; hours: "h",
setLocalSettings({ ...localSettings, logLevel: newLogLevel }); };
}; const unitItems = Object.keys(unitItemLookup).map((key) => ({
_id: unitItemLookup[key],
name: key,
}));
const handleChange = (event) => { const handleLogLevel = (e) => {
const { value, id } = event.target; const id = e.target.value;
setLocalSettings({ ...localSettings, [id]: value }); const newLogLevel = logItems.find((item) => item._id === id).name;
}; setLocalSettings({ ...localSettings, logLevel: newLogLevel });
};
const handleSave = async () => { const handleJWTTTLUnits = (e) => {
const action = await dispatch( const id = e.target.value;
updateAppSettings({ settings: localSettings, authToken }) const newUnits = unitItems.find((item) => item._id === id).name;
); setLocalSettings({ ...localSettings, jwtTTLUnits: newUnits });
let body = ""; };
if (action.payload.success) {
console.log(action.payload.data);
setLocalSettings(action.payload.data);
body = "Settings saved successfully";
} else {
body = "Failed to save settings";
}
createToast({ body });
};
return ( const handleBlur = (event) => {
<Box const { value, id } = event.target;
className="settings" const { error } = advancedSettingsValidation.validate(
style={{ { [id]: value },
paddingBottom: 0, {
}} abortEarly: false,
> }
<Stack );
component="form" setErrors((prev) => {
gap={theme.spacing(12)} return buildErrors(prev, id, error);
noValidate });
spellCheck="false" };
> const handleChange = (event) => {
<ConfigBox> const { value, id } = event.target;
<Box> setLocalSettings({ ...localSettings, [id]: value });
<Typography component="h1">Client settings</Typography> };
<Typography sx={{ mt: theme.spacing(2) }}>
Modify client settings here. const handleSave = async () => {
</Typography> localSettings.jwtTTL =
</Box> localSettings.jwtTTLNum + unitItemLookup[localSettings.jwtTTLUnits];
<Stack gap={theme.spacing(20)}> if (hasValidationErrors(localSettings, advancedSettingsValidation, setErrors)) {
<Field return;
id="apiBaseUrl" }
label="API URL Host" const action = await dispatch(
value={localSettings.apiBaseUrl} updateAppSettings({ settings: localSettings, authToken })
onChange={handleChange} );
/> let body = "";
<Select if (action.payload.success) {
id="logLevel" parseJWTTTL(action.payload.data);
label="Log level" setLocalSettings(action.payload.data);
name="logLevel" body = "Settings saved successfully";
items={logItems} } else {
value={logItemLookup[localSettings.logLevel]} body = "Failed to save settings";
onChange={handleLogLevel} }
/> createToast({ body });
</Stack> };
</ConfigBox>
<ConfigBox> return (
<Box> <Box
<Typography component="h1">Email settings</Typography> className="settings"
<Typography sx={{ mt: theme.spacing(2) }}> style={{
Set your host email settings here. These settings are used for paddingBottom: 0,
sending system emails. }}
</Typography> >
</Box> <Stack
<Stack gap={theme.spacing(20)}> component="form"
<Field gap={theme.spacing(12)}
type="text" noValidate
id="systemEmailHost" spellCheck="false"
label="Email host" >
name="systemEmailHost" <ConfigBox>
value={localSettings.systemEmailHost} <Box>
onChange={handleChange} <Typography component="h1">Client settings</Typography>
/> <Typography sx={{ mt: theme.spacing(2) }}>
<Field Modify client settings here.
type="number" </Typography>
id="systemEmailPort" </Box>
label="System email address" <Stack gap={theme.spacing(20)}>
name="systemEmailPort" <Field
value={localSettings.systemEmailPort.toString()} id="apiBaseUrl"
onChange={handleChange} label="API URL Host"
/> value={localSettings.apiBaseUrl}
<Field onChange={handleChange}
type="email" onBlur={handleBlur}
id="systemEmailAddress" error={errors.apiBaseUrl}
label="System email address" />
name="systemEmailAddress" <Select
value={localSettings.systemEmailAddress} id="logLevel"
onChange={handleChange} label="Log level"
/> name="logLevel"
<Field items={logItems}
type="text" value={logItemLookup[localSettings.logLevel]}
id="systemEmailPassword" onChange={handleLogLevel}
label="System email password" onBlur={handleBlur}
name="systemEmailPassword" error={errors.logLevel}
value={localSettings.systemEmailPassword} />
onChange={handleChange} </Stack>
/> </ConfigBox>
</Stack> <ConfigBox>
</ConfigBox> <Box>
<ConfigBox> <Typography component="h1">Email settings</Typography>
<Box> <Typography sx={{ mt: theme.spacing(2) }}>
<Typography component="h1">Server settings</Typography> Set your host email settings here. These settings are used for sending
<Typography sx={{ mt: theme.spacing(2) }}> system emails.
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="systemEmailHost"
id="jwtTTL" label="System email host"
label="JWT time to live" name="systemEmailHost"
name="jwtTTL" value={localSettings.systemEmailHost}
value={localSettings.jwtTTL} onChange={handleChange}
onChange={handleChange} onBlur={handleBlur}
/> error={errors.systemEmailHost}
<Field />
type="text" <Field
id="dbType" type="number"
label="Database type" id="systemEmailPort"
name="dbType" label="System email port"
value={localSettings.dbType} name="systemEmailPort"
onChange={handleChange} value={localSettings.systemEmailPort?.toString()}
/> onChange={handleChange}
<Field onBlur={handleBlur}
type="text" error={errors.systemEmailPort}
id="redisHost" />
label="Redis host" <Field
name="redisHost" type="email"
value={localSettings.redisHost} id="systemEmailAddress"
onChange={handleChange} label="System email address"
/> name="systemEmailAddress"
<Field value={localSettings.systemEmailAddress}
type="number" onChange={handleChange}
id="redisPort" error={errors.systemEmailAddress}
label="Redis port" />
name="redisPort" <Field
value={localSettings.redisPort.toString()} type="text"
onChange={handleChange} id="systemEmailPassword"
/> label="System email password"
<Field name="systemEmailPassword"
type="text" value={localSettings.systemEmailPassword}
id="pagespeedApiKey" onChange={handleChange}
label="PageSpeed API key" onBlur={handleBlur}
name="pagespeedApiKey" error={errors.systemEmailPassword}
value={localSettings.pagespeedApiKey} />
onChange={handleChange} </Stack>
/> </ConfigBox>
</Stack> <ConfigBox>
</ConfigBox> <Box>
<ConfigBox> <Typography component="h1">Server settings</Typography>
<Box> <Typography sx={{ mt: theme.spacing(2) }}>
<Typography component="h1">About</Typography> Modify server settings here.
</Box> </Typography>
<Box> </Box>
<Typography component="h2">BlueWave Uptime v1.0.0</Typography> <Stack gap={theme.spacing(20)}>
<Typography <Stack
sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }} direction="row"
> gap={theme.spacing(10)}
Developed by Bluewave Labs. >
</Typography> <Field
<Link type="number"
level="secondary" id="jwtTTLNum"
url="https://github.com/bluewave-labs" label="JWT time to live"
label="https://github.com/bluewave-labs" name="jwtTTLNum"
/> value={localSettings.jwtTTLNum.toString()}
</Box> onChange={handleChange}
</ConfigBox> onBlur={handleBlur}
<Stack direction="row" justifyContent="flex-end"> error={errors.jwtTTLNum}
<LoadingButton />
loading={settings.isLoading || settings.authIsLoading} <Select
variant="contained" id="jwtTTLUnits"
color="primary" label="JWT TTL Units"
sx={{ px: theme.spacing(12), mt: theme.spacing(20) }} name="jwtTTLUnits"
onClick={handleSave} placeholder="Select time"
> isHidden={true}
Save items={unitItems}
</LoadingButton> value={unitItemLookup[localSettings.jwtTTLUnits]}
</Stack> onChange={handleJWTTTLUnits}
</Stack> onBlur={handleBlur}
</Box> error={errors.jwtTTLUnits}
); />
</Stack>
<Field
type="text"
id="dbType"
label="Database type"
name="dbType"
value={localSettings.dbType}
onChange={handleChange}
onBlur={handleBlur}
error={errors.dbType}
/>
<Field
type="text"
id="redisHost"
label="Redis host"
name="redisHost"
value={localSettings.redisHost}
onChange={handleChange}
onBlur={handleBlur}
error={errors.redisHost}
/>
<Field
type="number"
id="redisPort"
label="Redis port"
name="redisPort"
value={localSettings.redisPort?.toString()}
onChange={handleChange}
onBlur={handleBlur}
error={errors.redisPort}
/>
<Field
type="text"
id="pagespeedApiKey"
label="PageSpeed API key"
name="pagespeedApiKey"
value={localSettings.pagespeedApiKey}
onChange={handleChange}
onBlur={handleBlur}
error={errors.pagespeedApiKey}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h1">About</Typography>
</Box>
<Box>
<Typography component="h2">BlueWave Uptime v1.0.0</Typography>
<Typography sx={{ mt: theme.spacing(2), mb: theme.spacing(6), opacity: 0.6 }}>
Developed by Bluewave Labs.
</Typography>
<Link
level="secondary"
url="https://github.com/bluewave-labs"
label="https://github.com/bluewave-labs"
/>
</Box>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton
loading={settings.isLoading || settings.authIsLoading}
variant="contained"
color="primary"
sx={{ px: theme.spacing(12), mt: theme.spacing(20) }}
onClick={handleSave}
>
Save
</LoadingButton>
</Stack>
</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,
}, },
}, },
})); }));
@@ -0,0 +1,32 @@
import { useTheme } from "@emotion/react";
import PlaceholderLight from "../../../../assets/Images/data_placeholder.svg?react";
import PlaceholderDark from "../../../../assets/Images/data_placeholder_dark.svg?react";
import { Box, Typography } from "@mui/material";
import PropTypes from "prop-types";
const Empty = ({ styles, mode }) => {
const theme = useTheme();
return (
<Box sx={{ ...styles }}>
<Box
textAlign="center"
pb={theme.spacing(20)}
>
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box>
<Typography
textAlign="center"
color={theme.palette.text.secondary}
>
No incidents recorded yet.
</Typography>
</Box>
);
};
Empty.propTypes = {
styles: PropTypes.object,
mode: PropTypes.string,
};
export { Empty };
@@ -0,0 +1,21 @@
import { Skeleton /* , Stack */ } from "@mui/material";
const IncidentSkeleton = () => {
return (
<>
<Skeleton
animation={"wave"}
variant="rounded"
width="100%"
height={300}
/>
<Skeleton
animation={"wave"}
variant="rounded"
width="100%"
height={100}
/>
</>
);
};
export { IncidentSkeleton };
+189 -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";
@@ -24,185 +24,197 @@ import { useTheme } from "@emotion/react";
import { formatDateWithTz } from "../../../Utils/timeUtils"; import { formatDateWithTz } from "../../../Utils/timeUtils";
import PlaceholderLight from "../../../assets/Images/data_placeholder.svg?react"; 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";
import { Empty } from "./Empty/Empty";
import { IncidentSkeleton } from "./Skeleton/Skeleton";
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,
}); });
const [isLoading, setIsLoading] = useState(true);
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; setIsLoading(true);
if (selectedMonitor === "0") { let res;
res = await networkService.getChecksByTeam({ if (selectedMonitor === "0") {
authToken: authToken, res = await networkService.getChecksByTeam({
teamId: user.teamId, authToken: authToken,
sortOrder: "desc", teamId: user.teamId,
limit: null, sortOrder: "desc",
dateRange: null, limit: null,
filter: filter, dateRange: null,
page: paginationController.page, filter: filter,
rowsPerPage: paginationController.rowsPerPage, page: paginationController.page,
}); rowsPerPage: paginationController.rowsPerPage,
} else { });
res = await networkService.getChecksByMonitor({ } else {
authToken: authToken, res = await networkService.getChecksByMonitor({
monitorId: selectedMonitor, authToken: authToken,
sortOrder: "desc", monitorId: selectedMonitor,
limit: null, sortOrder: "desc",
dateRange: null, limit: null,
sitler: filter, dateRange: null,
page: paginationController.page, filter: filter,
rowsPerPage: paginationController.rowsPerPage, page: paginationController.page,
}); rowsPerPage: paginationController.rowsPerPage,
} });
setChecks(res.data.data.checks); }
setChecksCount(res.data.data.checksCount); setChecks(res.data.data.checks);
} catch (error) { setChecksCount(res.data.data.checksCount);
logger.error(error); } catch (error) {
} logger.error(error);
}; } finally {
fetchPage(); setIsLoading(false);
}, [ }
authToken, };
user, fetchPage();
monitors, }, [
selectedMonitor, authToken,
filter, user,
paginationController.page, monitors,
paginationController.rowsPerPage, selectedMonitor,
]); filter,
paginationController.page,
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 ( const hasChecks = checks?.length === 0;
<> const noIncidentsRecordedYet = hasChecks && selectedMonitor === "0";
{checks?.length === 0 && selectedMonitor === "0" ? ( const noIncidentsForThatMonitor = hasChecks && selectedMonitor !== "0";
<Box sx={{ ...sharedStyles }}>
<Box textAlign="center" pb={theme.spacing(20)}>
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box>
<Typography textAlign="center" color={theme.palette.text.secondary}>
No incidents recorded yet.
</Typography>
</Box>
) : checks?.length === 0 ? (
<Box sx={{ ...sharedStyles }}>
<Box textAlign="center" pb={theme.spacing(20)}>
{mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
</Box>
<Typography textAlign="center" color={theme.palette.text.secondary}>
The monitor you have selected has no recorded incidents yet.
</Typography>
</Box>
) : (
<>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Monitor Name</TableCell>
<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}> <>
<TableCell>{monitors[check.monitorId]?.name}</TableCell> {isLoading ? (
<TableCell> <IncidentSkeleton />
<StatusLabel ) : noIncidentsRecordedYet ? (
status={status} <Empty
text={status} mode={mode}
customStyles={{ textTransform: "capitalize" }} styles={sharedStyles}
/> />
</TableCell> ) : noIncidentsForThatMonitor ? (
<TableCell>{formattedDate}</TableCell> <Box sx={{ ...sharedStyles }}>
<TableCell> <Box
{check.statusCode ? check.statusCode : "N/A"} textAlign="center"
</TableCell> pb={theme.spacing(20)}
<TableCell>{check.message}</TableCell> >
</TableRow> {mode === "light" ? <PlaceholderLight /> : <PlaceholderDark />}
); </Box>
})} <Typography
</TableBody> textAlign="center"
</Table> color={theme.palette.text.secondary}
</TableContainer> >
{paginationComponent} The monitor you have selected has no recorded incidents yet.
</> </Typography>
)} </Box>
</> ) : (
); <>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Monitor Name</TableCell>
<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 (
<TableRow key={check._id}>
<TableCell>{monitors[check.monitorId]?.name}</TableCell>
<TableCell>
<StatusLabel
status={status}
text={status}
customStyles={{ textTransform: "capitalize" }}
/>
</TableCell>
<TableCell>{formattedDate}</TableCell>
<TableCell>{check.statusCode ? check.statusCode : "N/A"}</TableCell>
<TableCell>{check.message}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</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;
} }
+120 -106
View File
@@ -11,119 +11,133 @@ 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 [isLoading, setIsLoading] = useState(true);
// 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); try {
const res = await networkService.getMonitorsByTeamId({ setIsLoading(true);
authToken: authState.authToken, const res = await networkService.getMonitorsByTeamId({
teamId: authState.user.teamId, authToken: authState.authToken,
limit: -1, teamId: authState.user.teamId,
types: null, limit: -1,
status: null, types: null,
checkOrder: null, status: null,
normalize: null, checkOrder: null,
page: null, normalize: null,
rowsPerPage: null, page: null,
filter: null, rowsPerPage: null,
field: null, filter: null,
order: null, field: null,
}); order: null,
// Reduce to a lookup object for 0(1) lookup });
if (res?.data?.data?.monitors?.length > 0) { // Reduce to a lookup object for 0(1) lookup
const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => { if (res?.data?.data?.monitors?.length > 0) {
acc[monitor._id] = monitor; const monitorLookup = res.data.data.monitors.reduce((acc, monitor) => {
return acc; acc[monitor._id] = monitor;
}, {}); return acc;
setMonitors(monitorLookup); }, {});
monitorId !== undefined && setSelectedMonitor(monitorId); setMonitors(monitorLookup);
} monitorId !== undefined && setSelectedMonitor(monitorId);
setLoading(false); }
}; } catch (error) {
console.info(error);
} finally {
setIsLoading(false);
}
};
fetchMonitors();
}, [authState]);
fetchMonitors(); useEffect(() => {}, [monitors]);
}, [authState]);
useEffect(() => {}, []); const handleSelect = (event) => {
setSelectedMonitor(event.target.value);
};
const handleSelect = (event) => { const isActuallyLoading = isLoading && Object.keys(monitors)?.length === 0;
setSelectedMonitor(event.target.value);
};
return ( return (
<Stack className="incidents" pt={theme.spacing(6)} gap={theme.spacing(12)}> <Stack
{loading ? ( className="incidents"
<SkeletonLayout /> pt={theme.spacing(6)}
) : ( gap={theme.spacing(12)}
<> >
<Stack direction="row" alignItems="center" gap={theme.spacing(6)}> {isActuallyLoading ? (
<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 },
})); }));
@@ -2,228 +2,175 @@ import { useState } from "react";
import { useTheme } from "@emotion/react"; 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 { IconButton, Menu, MenuItem } from "@mui/material";
Button,
IconButton,
Menu,
MenuItem,
Modal,
Stack,
Typography,
} from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import { logger } from "../../../../Utils/Logger"; import { logger } from "../../../../Utils/Logger";
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 { networkService } from "../../../../main"; import { networkService } from "../../../../main";
import { createToast } from "../../../../Utils/toastUtils"; import { createToast } from "../../../../Utils/toastUtils";
const ActionsMenu = ({ isAdmin, maintenanceWindow, updateCallback }) => { import Dialog from "../../../../Components/Dialog";
maintenanceWindow;
const { authToken } = useSelector((state) => state.auth);
const [anchorEl, setAnchorEl] = useState(null);
const [isOpen, setIsOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const theme = useTheme(); const ActionsMenu = ({ /* isAdmin, */ maintenanceWindow, updateCallback }) => {
maintenanceWindow;
const { authToken } = useSelector((state) => state.auth);
const [anchorEl, setAnchorEl] = useState(null);
const [isOpen, setIsOpen] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const handleRemove = async (event) => { const theme = useTheme();
event.preventDefault();
event.stopPropagation();
try {
setIsLoading(true);
await networkService.deleteMaintenanceWindow({
authToken,
maintenanceWindowId: maintenanceWindow._id,
});
updateCallback();
createToast({ body: "Maintenance window deleted successfully." });
} catch (error) {
createToast({ body: "Failed to delete maintenance window." });
logger.error("Failed to delete maintenance window", error);
} finally {
setIsLoading(false);
}
setIsOpen(false);
};
const handlePause = async () => { const handleRemove = async (event) => {
try { event.preventDefault();
setIsLoading(true); event.stopPropagation();
const data = { try {
active: !maintenanceWindow.active, setIsLoading(true);
}; await networkService.deleteMaintenanceWindow({
await networkService.editMaintenanceWindow({ authToken,
authToken, maintenanceWindowId: maintenanceWindow._id,
maintenanceWindowId: maintenanceWindow._id, });
maintenanceWindow: data, updateCallback();
}); createToast({ body: "Maintenance window deleted successfully." });
updateCallback(); } catch (error) {
} catch (error) { createToast({ body: "Failed to delete maintenance window." });
logger.error(error); logger.error("Failed to delete maintenance window", error);
createToast({ body: "Failed to pause maintenance window." }); } finally {
} finally { setIsLoading(false);
setIsLoading(false); }
} setIsOpen(false);
}; };
const handleEdit = () => { const handlePause = async () => {
navigate(`/maintenance/create/${maintenanceWindow._id}`); try {
}; setIsLoading(true);
const data = {
active: !maintenanceWindow.active,
};
await networkService.editMaintenanceWindow({
authToken,
maintenanceWindowId: maintenanceWindow._id,
maintenanceWindow: data,
});
updateCallback();
} catch (error) {
logger.error(error);
createToast({ body: "Failed to pause maintenance window." });
} finally {
setIsLoading(false);
}
};
const openMenu = (event) => { const handleEdit = () => {
event.preventDefault(); navigate(`/maintenance/create/${maintenanceWindow._id}`);
event.stopPropagation(); };
setAnchorEl(event.currentTarget);
};
const openRemove = (e) => { const openMenu = (event) => {
closeMenu(e); event.preventDefault();
setIsOpen(true); event.stopPropagation();
}; setAnchorEl(event.currentTarget);
};
const closeMenu = (e) => { const openRemove = (e) => {
e.stopPropagation(); closeMenu(e);
setAnchorEl(null); setIsOpen(true);
}; };
const navigate = useNavigate(); const closeMenu = (e) => {
e.stopPropagation();
setAnchorEl(null);
};
return ( const navigate = useNavigate();
<>
<IconButton
aria-label="monitor actions"
onClick={(event) => {
event.stopPropagation();
openMenu(event);
}}
sx={{
"&:focus": {
outline: "none",
},
"& svg path": {
stroke: theme.palette.other.icon,
},
}}
>
<Settings />
</IconButton>
<Menu return (
className="actions-menu" <>
anchorEl={anchorEl} <IconButton
open={Boolean(anchorEl)} aria-label="monitor actions"
onClose={(e) => closeMenu(e)} onClick={(event) => {
disableScrollLock event.stopPropagation();
slotProps={{ openMenu(event);
paper: { }}
sx: { sx={{
"& ul": { p: theme.spacing(2.5) }, "&:focus": {
"& li": { m: 0 }, outline: "none",
"& li:last-of-type": { },
color: theme.palette.error.text, "& svg path": {
}, stroke: theme.palette.other.icon,
}, },
}, }}
}} >
> <Settings />
<MenuItem </IconButton>
onClick={(e) => {
closeMenu(e);
e.stopPropagation();
handleEdit();
}}
>
Edit
</MenuItem>
<MenuItem
onClick={(e) => {
handlePause();
closeMenu(e);
e.stopPropagation();
}}
>
{`${maintenanceWindow.active === true ? "Pause" : "Resume"}`}
</MenuItem>
<MenuItem <Menu
onClick={(e) => { className="actions-menu"
e.stopPropagation(); anchorEl={anchorEl}
openRemove(e); open={Boolean(anchorEl)}
}} onClose={(e) => closeMenu(e)}
> disableScrollLock
Remove slotProps={{
</MenuItem> paper: {
</Menu> sx: {
<Modal "& ul": { p: theme.spacing(2.5) },
aria-labelledby="modal-delete-monitor" "& li": { m: 0 },
aria-describedby="delete-monitor-confirmation" "& li:last-of-type": {
open={isOpen} color: theme.palette.error.text,
onClose={(e) => { },
e.stopPropagation(); },
setIsOpen(false); },
}} }}
> >
<Stack <MenuItem
gap={theme.spacing(2)} onClick={(e) => {
sx={{ closeMenu(e);
position: "absolute", e.stopPropagation();
top: "50%", handleEdit();
left: "50%", }}
transform: "translate(-50%, -50%)", >
width: 400, Edit
bgcolor: theme.palette.background.main, </MenuItem>
border: 1, <MenuItem
borderColor: theme.palette.border.light, onClick={(e) => {
borderRadius: theme.shape.borderRadius, handlePause();
boxShadow: 24, closeMenu(e);
p: theme.spacing(15), e.stopPropagation();
"&:focus": { }}
outline: "none", >
}, {`${maintenanceWindow.active === true ? "Pause" : "Resume"}`}
}} </MenuItem>
>
<Typography id="modal-delete-maintenance" component="h2" variant="h2"> <MenuItem
Do you really want to remove this maintenance window? onClick={(e) => {
</Typography> e.stopPropagation();
<Stack openRemove(e);
direction="row" }}
gap={theme.spacing(4)} >
mt={theme.spacing(12)} Remove
justifyContent="flex-end" </MenuItem>
> </Menu>
<Button <Dialog
variant="text" open={isOpen}
color="info" theme={theme}
onClick={(e) => { title={"Do you really want to remove this maintenance window?"}
e.stopPropagation(); onCancel={(e) => {
setIsOpen(false); e.stopPropagation();
}} setIsOpen(false);
> }}
Cancel confirmationButtonLabel={"Delete"}
</Button> onConfirm={(e) => {
<LoadingButton e.stopPropagation(e);
loading={isLoading} handleRemove(e);
variant="contained" }}
color="error" isLoading={isLoading}
onClick={(e) => { />
e.stopPropagation(e); </>
handleRemove(e); );
}}
>
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" 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%;
} }
+418 -466
View File
@@ -2,17 +2,17 @@ import { useNavigate, useParams } from "react-router";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Box, Button, Modal, Stack, Tooltip, Typography } from "@mui/material"; import { Box, Stack, Tooltip, Typography } from "@mui/material";
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils"; 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";
@@ -24,6 +24,7 @@ import PulseDot from "../../../Components/Animated/PulseDot";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import "./index.css"; import "./index.css";
import Dialog from "../../../Components/Dialog";
/** /**
* Parses a URL string and returns a URL object. * Parses a URL string and returns a URL object.
@@ -32,11 +33,11 @@ import "./index.css";
* @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;
} }
}; };
/** /**
@@ -44,476 +45,427 @@ 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
<Modal variant="contained"
aria-labelledby="modal-delete-monitor" color="primary"
aria-describedby="delete-monitor-confirmation" loading={isLoading}
open={isOpen} sx={{ px: theme.spacing(12) }}
onClose={() => setIsOpen(false)} onClick={handleSubmit}
disablePortal >
> Save
<Stack </LoadingButton>
gap={theme.spacing(2)} </Stack>
sx={{ </Stack>
position: "absolute", </>
top: "50%", )}
left: "50%",
transform: "translate(-50%, -50%)", <Dialog
width: 400, open={isOpen}
bgcolor: theme.palette.background.main, theme={theme}
border: 1, title="Do you really want to delete this monitor?"
borderColor: theme.palette.border.light, description="Once deleted, this monitor cannot be retrieved."
borderRadius: theme.shape.borderRadius, onCancel={() => setIsOpen(false)}
boxShadow: 24, confirmationButtonLabel="Delete"
p: theme.spacing(15), onConfirm={handleRemove}
"&:focus": { isLoading={isLoading}
outline: "none", />
}, </Stack>
}} );
>
<Typography
id="modal-delete-monitor"
component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}
>
Do you really want to delete this monitor?
</Typography>
<Typography
id="delete-monitor-confirmation"
color={theme.palette.text.tertiary}
>
Once deleted, this monitor cannot be retrieved.
</Typography>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={() => setIsOpen(false)}
>
Cancel
</Button>
<LoadingButton
variant="contained"
color="error"
loading={isLoading}
onClick={handleRemove}
>
Delete
</LoadingButton>
</Stack>
</Stack>
</Modal>
</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;
+363 -345
View File
@@ -1,8 +1,10 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Box, Button, ButtonGroup, Stack, Typography } from "@mui/material"; import { Box, Button, ButtonGroup, Stack, Typography } from "@mui/material";
import LoadingButton from '@mui/lab/LoadingButton';
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { createUptimeMonitor } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; import { createUptimeMonitor } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import { checkEndpointResolution } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
@@ -19,368 +21,384 @@ import "./index.css";
const CreateMonitor = () => { const CreateMonitor = () => {
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 { monitors } = useSelector((state) => state.uptimeMonitors); const { monitors, isLoading } = useSelector((state) => state.uptimeMonitors);
const dispatch = useDispatch(); const dispatch = useDispatch();
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();
}, [monitorId, authToken, monitors]);
const handleChange = (event, name) => {
const { value, id } = event.target;
if (!name) name = idMap[id];
if (name.includes("notification-")) {
name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some(
(notification) => notification.type === name
);
setMonitor((prev) => {
const notifs = [...prev.notifications];
if (hasNotif) {
return {
...prev,
notifications: notifs.filter((notif) => notif.type !== name),
};
} else {
return {
...prev,
notifications: [
...notifs,
name === "email"
? { type: name, address: value }
: // TODO - phone number
{ type: name, phone: value },
],
};
}
});
} else {
setMonitor((prev) => ({
...prev,
[name]: value,
}));
const { error } = monitorValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
console.log(error);
setErrors((prev) => {
const updatedErrors = { ...prev };
if (error) updatedErrors[name] = error.details[0].message;
else delete updatedErrors[name];
return updatedErrors;
});
}
};
const handleCreateMonitor = async (event) => {
event.preventDefault();
//obj to submit
let form = {
url:
//preprending protocol for url
monitor.type === "http"
? `http${https ? "s" : ""}://` + monitor.url
: monitor.url,
name: monitor.name === "" ? monitor.url : monitor.name,
type: monitor.type,
interval: monitor.interval * MS_PER_MINUTE,
};
const { error } = monitorValidation.validate(form, {
abortEarly: false,
});
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
createToast({ body: "Error validation data." });
} else {
if (monitor.type === "http") {
const checkEndpointAction = await dispatch(
checkEndpointResolution({ authToken, monitorURL: form.url })
)
if (checkEndpointAction.meta.requestStatus === "rejected") {
createToast({ body: "The endpoint you entered doesn't resolve. Check the URL again." });
setErrors({ url: "The entered URL is not reachable." });
return;
} }
} }
};
fetchMonitor();
}, [monitorId, authToken, monitors]);
const handleChange = (event, name) => { form = {
const { value, id } = event.target; ...form,
if (!name) name = idMap[id]; description: form.name,
teamId: user.teamId,
userId: user._id,
notifications: monitor.notifications,
};
const action = await dispatch(createUptimeMonitor({ authToken, monitor: form }));
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" });
navigate("/monitors");
} else {
createToast({ body: "Failed to create monitor." });
}
}
};
if (name.includes("notification-")) { //select values
name = name.replace("notification-", ""); const frequencies = [
let hasNotif = monitor.notifications.some( { _id: 1, name: "1 minute" },
(notification) => notification.type === name { _id: 2, name: "2 minutes" },
); { _id: 3, name: "3 minutes" },
setMonitor((prev) => { { _id: 4, name: "4 minutes" },
const notifs = [...prev.notifications]; { _id: 5, name: "5 minutes" },
if (hasNotif) { ];
return {
...prev,
notifications: notifs.filter((notif) => notif.type !== name),
};
} else {
return {
...prev,
notifications: [
...notifs,
name === "email"
? { type: name, address: value }
: // TODO - phone number
{ type: name, phone: value },
],
};
}
});
} else {
setMonitor((prev) => ({
...prev,
[name]: value,
}));
const { error } = monitorValidation.validate( return (
{ [name]: value }, <Box className="create-monitor">
{ abortEarly: false } <Breadcrumbs
); list={[
console.log(error); { name: "monitors", path: "/monitors" },
setErrors((prev) => { { name: "create", path: `/monitors/create` },
const updatedErrors = { ...prev }; ]}
if (error) updatedErrors[name] = error.details[0].message; />
else delete updatedErrors[name]; <Stack
return updatedErrors; component="form"
}); className="create-monitor-form"
} onSubmit={handleCreateMonitor}
}; noValidate
spellCheck="false"
const handleCreateMonitor = async (event) => { gap={theme.spacing(12)}
event.preventDefault(); mt={theme.spacing(6)}
//obj to submit >
let form = { <Typography
url: component="h1"
//preprending protocol for url variant="h1"
monitor.type === "http" >
? `http${https ? "s" : ""}://` + monitor.url <Typography
: monitor.url, component="span"
name: monitor.name === "" ? monitor.url : monitor.name, fontSize="inherit"
type: monitor.type, >
interval: monitor.interval * MS_PER_MINUTE, Create your{" "}
}; </Typography>
<Typography
const { error } = monitorValidation.validate(form, { component="span"
abortEarly: false, variant="h2"
}); fontSize="inherit"
fontWeight="inherit"
if (error) { >
const newErrors = {}; monitor
error.details.forEach((err) => { </Typography>
newErrors[err.path[0]] = err.message; </Typography>
}); <ConfigBox>
setErrors(newErrors); <Box>
createToast({ body: "Error validation data." }); <Typography component="h2">General settings</Typography>
} else { <Typography component="p">
form = { Here you can select the URL of the host, together with the type of monitor.
...form, </Typography>
description: form.name, </Box>
teamId: user.teamId, <Stack gap={theme.spacing(15)}>
userId: user._id, <Field
notifications: monitor.notifications, type={monitor.type === "http" ? "url" : "text"}
}; id="monitor-url"
const action = await dispatch( label="URL to monitor"
createUptimeMonitor({ authToken, monitor: form }) https={https}
); placeholder="google.com"
if (action.meta.requestStatus === "fulfilled") { value={monitor.url}
createToast({ body: "Monitor created successfully!" }); onChange={handleChange}
navigate("/monitors"); error={errors["url"]}
} else { />
createToast({ body: "Failed to create monitor." }); <Field
} type="text"
} id="monitor-name"
}; label="Display name"
isOptional={true}
//select values placeholder="Google"
const frequencies = [ value={monitor.name}
{ _id: 1, name: "1 minute" }, onChange={handleChange}
{ _id: 2, name: "2 minutes" }, error={errors["name"]}
{ _id: 3, name: "3 minutes" }, />
{ _id: 4, name: "4 minutes" }, </Stack>
{ _id: 5, name: "5 minutes" }, </ConfigBox>
]; <ConfigBox>
<Box>
return ( <Typography component="h2">Checks to perform</Typography>
<Box className="create-monitor"> <Typography component="p">
<Breadcrumbs You can always add or remove checks after adding your site.
list={[ </Typography>
{ name: "monitors", path: "/monitors" }, </Box>
{ name: "create", path: `/monitors/create` }, <Stack gap={theme.spacing(12)}>
]} <Stack gap={theme.spacing(6)}>
/> <Radio
<Stack id="monitor-checks-http"
component="form" title="Website monitoring"
className="create-monitor-form" desc="Use HTTP(s) to monitor your website or API endpoint."
onSubmit={handleCreateMonitor} size="small"
noValidate value="http"
spellCheck="false" checked={monitor.type === "http"}
gap={theme.spacing(12)} onChange={(event) => handleChange(event)}
mt={theme.spacing(6)} />
> {monitor.type === "http" ? (
<Typography component="h1" variant="h1"> <ButtonGroup sx={{ ml: theme.spacing(16) }}>
<Typography component="span" fontSize="inherit"> <Button
Create your{" "} variant="group"
</Typography> filled={https.toString()}
<Typography onClick={() => setHttps(true)}
component="span" >
variant="h2" HTTPS
fontSize="inherit" </Button>
fontWeight="inherit" <Button
> variant="group"
monitor filled={(!https).toString()}
</Typography> onClick={() => setHttps(false)}
</Typography> >
<ConfigBox> HTTP
<Box> </Button>
<Typography component="h2">General settings</Typography> </ButtonGroup>
<Typography component="p"> ) : (
Here you can select the URL of the host, together with the type of ""
monitor. )}
</Typography> </Stack>
</Box> <Radio
<Stack gap={theme.spacing(15)}> id="monitor-checks-ping"
<Field title="Ping monitoring"
type={monitor.type === "http" ? "url" : "text"} desc="Check whether your server is available or not."
id="monitor-url" size="small"
label="URL to monitor" value="ping"
https={https} checked={monitor.type === "ping"}
placeholder="google.com" onChange={(event) => handleChange(event)}
value={monitor.url} />
onChange={handleChange} {errors["type"] ? (
error={errors["url"]} <Box className="error-container">
/> <Typography
<Field component="p"
type="text" className="input-error"
id="monitor-name" color={theme.palette.error.text}
label="Display name" >
isOptional={true} {errors["type"]}
placeholder="Google" </Typography>
value={monitor.name} </Box>
onChange={handleChange} ) : (
error={errors["name"]} ""
/> )}
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h2">Checks to perform</Typography> <Typography component="h2">Incident notifications</Typography>
<Typography component="p"> <Typography component="p">
You can always add or remove checks after adding your site. When there is an incident, notify users.
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(12)}> <Stack gap={theme.spacing(6)}>
<Stack gap={theme.spacing(6)}> <Typography component="p">When there is a new incident,</Typography>
<Radio <Checkbox
id="monitor-checks-http" id="notify-sms"
title="Website monitoring" label="Notify via SMS (coming soon)"
desc="Use HTTP(s) to monitor your website or API endpoint." isChecked={false}
size="small" value=""
value="http" onChange={() => logger.warn("disabled")}
checked={monitor.type === "http"} isDisabled={true}
onChange={(event) => handleChange(event)} />
/> <Checkbox
{monitor.type === "http" ? ( id="notify-email-default"
<ButtonGroup sx={{ ml: theme.spacing(16) }}> label={`Notify via email (to ${user.email})`}
<Button isChecked={monitor.notifications.some(
variant="group" (notification) => notification.type === "email"
filled={https.toString()} )}
onClick={() => setHttps(true)} value={user?.email}
> onChange={(event) => handleChange(event)}
HTTPS />
</Button> <Checkbox
<Button id="notify-email"
variant="group" label="Also notify via email to multiple addresses (coming soon)"
filled={(!https).toString()} isChecked={false}
onClick={() => setHttps(false)} value=""
> onChange={() => logger.warn("disabled")}
HTTP isDisabled={true}
</Button> />
</ButtonGroup> {monitor.notifications.some(
) : ( (notification) => notification.type === "emails"
"" ) ? (
)} <Box mx={theme.spacing(16)}>
</Stack> <Field
<Radio id="notify-email-list"
id="monitor-checks-ping" type="text"
title="Ping monitoring" placeholder="name@gmail.com"
desc="Check whether your server is available or not." value=""
size="small" onChange={() => logger.warn("disabled")}
value="ping" />
checked={monitor.type === "ping"} <Typography mt={theme.spacing(4)}>
onChange={(event) => handleChange(event)} You can separate multiple emails with a comma
/> </Typography>
{errors["type"] ? ( </Box>
<Box className="error-container"> ) : (
<Typography ""
component="p" )}
className="input-error" </Stack>
color={theme.palette.error.text} </ConfigBox>
> <ConfigBox>
{errors["type"]} <Box>
</Typography> <Typography component="h2">Advanced settings</Typography>
</Box> </Box>
) : ( <Stack gap={theme.spacing(12)}>
"" <Select
)} id="monitor-interval"
</Stack> label="Check frequency"
</ConfigBox> value={monitor.interval || 1}
<ConfigBox> onChange={(event) => handleChange(event, "interval")}
<Box> items={frequencies}
<Typography component="h2">Incident notifications</Typography> />
<Typography component="p"> </Stack>
When there is an incident, notify users. </ConfigBox>
</Typography> <Stack
</Box> direction="row"
<Stack gap={theme.spacing(6)}> justifyContent="flex-end"
<Typography component="p">When there is a new incident,</Typography> >
<Checkbox <LoadingButton
id="notify-sms"
label="Notify via SMS (coming soon)"
isChecked={false}
value=""
onChange={() => logger.warn("disabled")}
isDisabled={true}
/>
<Checkbox
id="notify-email-default"
label={`Notify via email (to ${user.email})`}
isChecked={monitor.notifications.some(
(notification) => notification.type === "email"
)}
value={user?.email}
onChange={(event) => handleChange(event)}
/>
<Checkbox
id="notify-email"
label="Also notify via email to multiple addresses (coming soon)"
isChecked={false}
value=""
onChange={() => logger.warn("disabled")}
isDisabled={true}
/>
{monitor.notifications.some(
(notification) => notification.type === "emails"
) ? (
<Box mx={theme.spacing(16)}>
<Field
id="notify-email-list"
type="text"
placeholder="name@gmail.com"
value=""
onChange={() => logger.warn("disabled")}
/>
<Typography mt={theme.spacing(4)}>
You can separate multiple emails with a comma
</Typography>
</Box>
) : (
""
)}
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Advanced settings</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
<Select
id="monitor-interval"
label="Check frequency"
value={monitor.interval || 1}
onChange={(event) => handleChange(event, "interval")}
items={frequencies}
/>
</Stack>
</ConfigBox>
<Stack direction="row" justifyContent="flex-end">
<Button
variant="contained" variant="contained"
color="primary" color="primary"
onClick={handleCreateMonitor} onClick={handleCreateMonitor}
disabled={Object.keys(errors).length !== 0 && true} disabled={Object.keys(errors).length !== 0 && true}
loading={isLoading}
> >
Create monitor Create monitor
</Button> </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 @@
+447 -441
View File
@@ -1,22 +1,19 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useEffect, useState, useCallback } from "react"; import { useEffect, useState, useCallback } from "react";
import { import {
Box, Box,
Button, Button,
Popover, Popover,
Stack, Stack,
Tooltip, Tooltip,
Typography, Typography,
useTheme, useTheme,
} from "@mui/material"; } from "@mui/material";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { networkService } from "../../../main"; import { networkService } from "../../../main";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { import { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
formatDurationRounded,
formatDurationSplit,
} from "../../../Utils/timeUtils";
import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart"; import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart";
import ButtonGroup from "@mui/material/ButtonGroup"; import ButtonGroup from "@mui/material/ButtonGroup";
import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
@@ -41,447 +38,456 @@ import { formatDateWithTz } from "../../../Utils/timeUtils";
* @component * @component
*/ */
const DetailsPage = ({ isAdmin }) => { const DetailsPage = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const { statusColor, statusStyles, statusMsg, determineState } = useUtils(); const { statusColor, statusStyles, statusMsg, determineState } = useUtils();
const [monitor, setMonitor] = useState({}); const [monitor, setMonitor] = useState({});
const { monitorId } = useParams(); const { monitorId } = useParams();
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const [dateRange, setDateRange] = useState("day"); const [dateRange, setDateRange] = useState("day");
const [certificateExpiry, setCertificateExpiry] = useState("N/A"); const [certificateExpiry, setCertificateExpiry] = useState("N/A");
const navigate = useNavigate(); const navigate = useNavigate();
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
const openCertificate = (event) => { const openCertificate = (event) => {
setAnchorEl(event.currentTarget); setAnchorEl(event.currentTarget);
}; };
const closeCertificate = () => { const closeCertificate = () => {
setAnchorEl(null); setAnchorEl(null);
}; };
const dateFormat = dateRange === "day" ? "MMM D, h A" : "MMM D"; const dateFormat = dateRange === "day" ? "MMM D, h A" : "MMM D";
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
const fetchMonitor = useCallback(async () => { const fetchMonitor = useCallback(async () => {
try { try {
const res = await networkService.getStatsByMonitorId({ const res = await networkService.getStatsByMonitorId({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
sortOrder: null, sortOrder: null,
limit: null, limit: null,
dateRange: dateRange, dateRange: dateRange,
numToDisplay: 50, numToDisplay: 50,
normalize: true, normalize: true,
}); });
setMonitor(res?.data?.data ?? {}); setMonitor(res?.data?.data ?? {});
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
navigate("/not-found", { replace: true }); navigate("/not-found", { replace: true });
} }
}, [authToken, monitorId, navigate, dateRange]); }, [authToken, monitorId, navigate, dateRange]);
useEffect(() => { useEffect(() => {
fetchMonitor(); fetchMonitor();
}, [fetchMonitor]); }, [fetchMonitor]);
useEffect(() => { useEffect(() => {
const fetchCertificate = async () => { const fetchCertificate = async () => {
if (monitor?.type !== "http") { if (monitor?.type !== "http") {
return; return;
} }
try { try {
const res = await networkService.getCertificateExpiry({ const res = await networkService.getCertificateExpiry({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
}); });
if (res?.data?.data?.certificateDate) {
const date = res.data.data.certificateDate;
setCertificateExpiry(formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A");
}
} catch (error) {
setCertificateExpiry("N/A");
console.error(error);
}
};
fetchCertificate();
}, [authToken, monitorId, monitor]);
if (res?.data?.data?.certificateDate) { const splitDuration = (duration) => {
let [month, day, year] = res.data.data.certificateDate.split("/"); const { time, format } = formatDurationSplit(duration);
const date = new Date(year, month - 1, day); return (
<>
{time}
<Typography component="span">{format}</Typography>
</>
);
};
setCertificateExpiry( let loading = Object.keys(monitor).length === 0;
formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A"
);
}
} catch (error) {
console.error(error);
}
};
fetchCertificate();
}, [authToken, monitorId, monitor]);
const splitDuration = (duration) => { const [hoveredUptimeData, setHoveredUptimeData] = useState(null);
const { time, format } = formatDurationSplit(duration); const [hoveredIncidentsData, setHoveredIncidentsData] = useState(null);
return (
<>
{time}
<Typography component="span">{format}</Typography>
</>
);
};
let loading = Object.keys(monitor).length === 0; return (
<Box className="monitor-details">
const [hoveredUptimeData, setHoveredUptimeData] = useState(null); {loading ? (
const [hoveredIncidentsData, setHoveredIncidentsData] = useState(null); <SkeletonLayout />
) : (
return ( <>
<Box className="monitor-details"> <Breadcrumbs
{loading ? ( list={[
<SkeletonLayout /> { name: "monitors", path: "/monitors" },
) : ( { name: "details", path: `/monitors/${monitorId}` },
<> ]}
<Breadcrumbs />
list={[ <Stack
{ name: "monitors", path: "/monitors" }, gap={theme.spacing(10)}
{ name: "details", path: `/monitors/${monitorId}` }, mt={theme.spacing(10)}
]} >
/> <Stack
<Stack gap={theme.spacing(10)} mt={theme.spacing(10)}> direction="row"
<Stack direction="row" gap={theme.spacing(2)}> gap={theme.spacing(2)}
<Box> >
<Typography component="h1" variant="h1"> <Box>
{monitor.name} <Typography
</Typography> component="h1"
<Stack variant="h1"
direction="row" >
alignItems="center" {monitor.name}
height="fit-content" </Typography>
gap={theme.spacing(2)} <Stack
> direction="row"
<Tooltip alignItems="center"
title={statusMsg[determineState(monitor)]} height="fit-content"
disableInteractive gap={theme.spacing(2)}
slotProps={{ >
popper: { <Tooltip
modifiers: [ title={statusMsg[determineState(monitor)]}
{ disableInteractive
name: "offset", slotProps={{
options: { popper: {
offset: [0, -8], modifiers: [
}, {
}, name: "offset",
], options: {
}, offset: [0, -8],
}} },
> },
<Box> ],
<PulseDot color={statusColor[determineState(monitor)]} /> },
</Box> }}
</Tooltip> >
<Typography component="h2" variant="h2"> <Box>
{monitor.url?.replace(/^https?:\/\//, "") || "..."} <PulseDot color={statusColor[determineState(monitor)]} />
</Typography> </Box>
<Typography </Tooltip>
position="relative" <Typography
variant="body2" component="h2"
mt={theme.spacing(1)} variant="h2"
ml={theme.spacing(6)} >
sx={{ {monitor.url?.replace(/^https?:\/\//, "") || "..."}
"&:before": { </Typography>
position: "absolute", <Typography
content: `""`, position="relative"
width: 4, variant="body2"
height: 4, mt={theme.spacing(1)}
borderRadius: "50%", ml={theme.spacing(6)}
backgroundColor: theme.palette.text.tertiary, sx={{
opacity: 0.8, "&:before": {
left: -9, position: "absolute",
top: "50%", content: `""`,
transform: "translateY(-50%)", width: 4,
}, height: 4,
}} borderRadius: "50%",
> backgroundColor: theme.palette.text.tertiary,
Checking every {formatDurationRounded(monitor?.interval)}. opacity: 0.8,
</Typography> left: -9,
</Stack> top: "50%",
</Box> transform: "translateY(-50%)",
<Stack },
direction="row" }}
height={34} >
sx={{ Checking every {formatDurationRounded(monitor?.interval)}.
ml: "auto", </Typography>
alignSelf: "flex-end", </Stack>
}} </Box>
> <Stack
<IconBox direction="row"
mr={theme.spacing(4)} height={34}
onClick={openCertificate} sx={{
sx={{ ml: "auto",
cursor: "pointer", alignSelf: "flex-end",
"& svg": { }}
width: 23, >
height: 23, <IconBox
top: "52%", mr={theme.spacing(4)}
}, onClick={openCertificate}
}} sx={{
> cursor: "pointer",
<CertificateIcon /> "& svg": {
</IconBox> width: 23,
<Popover height: 23,
id="certificate-dropdown" top: "52%",
anchorEl={anchorEl} },
open={Boolean(anchorEl)} }}
onClose={closeCertificate} >
disableScrollLock <CertificateIcon />
marginThreshold={null} </IconBox>
anchorOrigin={{ <Popover
vertical: "bottom", id="certificate-dropdown"
horizontal: "center", anchorEl={anchorEl}
}} open={Boolean(anchorEl)}
transformOrigin={{ onClose={closeCertificate}
vertical: "top", disableScrollLock
horizontal: "center", marginThreshold={null}
}} anchorOrigin={{
slotProps={{ vertical: "bottom",
paper: { horizontal: "center",
sx: { }}
mt: theme.spacing(4), transformOrigin={{
py: theme.spacing(2), vertical: "top",
px: theme.spacing(4), horizontal: "center",
width: 140, }}
backgroundColor: theme.palette.background.accent, slotProps={{
}, paper: {
}, sx: {
}} mt: theme.spacing(4),
> py: theme.spacing(2),
<Typography variant="body2">Certificate Expiry</Typography> px: theme.spacing(4),
<Typography width: 140,
component="span" backgroundColor: theme.palette.background.accent,
fontSize={13} },
color={theme.palette.text.primary} },
> }}
{certificateExpiry} >
</Typography> <Typography variant="body2">Certificate Expiry</Typography>
</Popover> <Typography
{isAdmin && ( component="span"
<Button fontSize={13}
variant="contained" color={theme.palette.text.primary}
color="secondary" >
onClick={() => navigate(`/monitors/configure/${monitorId}`)} {certificateExpiry}
sx={{ </Typography>
px: theme.spacing(5), </Popover>
"& svg": { {isAdmin && (
mr: theme.spacing(3), <Button
"& path": { variant="contained"
stroke: theme.palette.text.tertiary, color="secondary"
}, onClick={() => navigate(`/monitors/configure/${monitorId}`)}
}, sx={{
}} px: theme.spacing(5),
> "& svg": {
<SettingsIcon /> Configure mr: theme.spacing(3),
</Button> "& path": {
)} stroke: theme.palette.text.tertiary,
</Stack> },
</Stack> },
<Stack direction="row" gap={theme.spacing(8)}> }}
<StatBox sx={statusStyles[determineState(monitor)]}> >
<Typography component="h2">active for</Typography> <SettingsIcon /> Configure
<Typography> </Button>
{splitDuration(monitor?.uptimeDuration)} )}
</Typography> </Stack>
</StatBox> </Stack>
<StatBox> <Stack
<Typography component="h2">last check</Typography> direction="row"
<Typography> gap={theme.spacing(8)}
{splitDuration(monitor?.lastChecked)} >
<Typography component="span">ago</Typography> <StatBox sx={statusStyles[determineState(monitor)]}>
</Typography> <Typography component="h2">active for</Typography>
</StatBox> <Typography>{splitDuration(monitor?.uptimeDuration)}</Typography>
<StatBox> </StatBox>
<Typography component="h2">last response time</Typography> <StatBox>
<Typography> <Typography component="h2">last check</Typography>
{monitor?.latestResponseTime} <Typography>
<Typography component="span">ms</Typography> {splitDuration(monitor?.lastChecked)}
</Typography> <Typography component="span">ago</Typography>
</StatBox> </Typography>
</Stack> </StatBox>
<Box> <StatBox>
<Stack <Typography component="h2">last response time</Typography>
direction="row" <Typography>
justifyContent="space-between" {monitor?.latestResponseTime}
alignItems="flex-end" <Typography component="span">ms</Typography>
gap={theme.spacing(4)} </Typography>
mb={theme.spacing(8)} </StatBox>
> </Stack>
<Typography variant="body2"> <Box>
Showing statistics for past{" "} <Stack
{dateRange === "day" direction="row"
? "24 hours" justifyContent="space-between"
: dateRange === "week" alignItems="flex-end"
? "7 days" gap={theme.spacing(4)}
: "30 days"} mb={theme.spacing(8)}
. >
</Typography> <Typography variant="body2">
<ButtonGroup sx={{ height: 32 }}> Showing statistics for past{" "}
<Button {dateRange === "day"
variant="group" ? "24 hours"
filled={(dateRange === "day").toString()} : dateRange === "week"
onClick={() => setDateRange("day")} ? "7 days"
> : "30 days"}
Day .
</Button> </Typography>
<Button <ButtonGroup sx={{ height: 32 }}>
variant="group" <Button
filled={(dateRange === "week").toString()} variant="group"
onClick={() => setDateRange("week")} filled={(dateRange === "day").toString()}
> onClick={() => setDateRange("day")}
Week >
</Button> Day
<Button </Button>
variant="group" <Button
filled={(dateRange === "month").toString()} variant="group"
onClick={() => setDateRange("month")} filled={(dateRange === "week").toString()}
> onClick={() => setDateRange("week")}
Month >
</Button> Week
</ButtonGroup> </Button>
</Stack> <Button
<Stack direction="row" flexWrap="wrap" gap={theme.spacing(8)}> variant="group"
<ChartBox> filled={(dateRange === "month").toString()}
<Stack> onClick={() => setDateRange("month")}
<IconBox> >
<UptimeIcon /> Month
</IconBox> </Button>
<Typography component="h2">Uptime</Typography> </ButtonGroup>
</Stack> </Stack>
<Stack justifyContent="space-between"> <Stack
<Box position="relative"> direction="row"
<Typography>Total Checks</Typography> flexWrap="wrap"
<Typography component="span"> gap={theme.spacing(8)}
{hoveredUptimeData !== null >
? hoveredUptimeData.totalChecks <ChartBox>
: monitor?.periodTotalChecks} <Stack>
</Typography> <IconBox>
{hoveredUptimeData !== null && <UptimeIcon />
hoveredUptimeData.time !== null && ( </IconBox>
<Typography <Typography component="h2">Uptime</Typography>
component="h5" </Stack>
position="absolute" <Stack justifyContent="space-between">
top="100%" <Box position="relative">
fontSize={11} <Typography>Total Checks</Typography>
color={theme.palette.text.tertiary} <Typography component="span">
> {hoveredUptimeData !== null
{formatDateWithTz( ? hoveredUptimeData.totalChecks
hoveredUptimeData.time, : monitor?.periodTotalChecks}
dateFormat, </Typography>
uiTimezone {hoveredUptimeData !== null && hoveredUptimeData.time !== null && (
)} <Typography
</Typography> component="h5"
)} position="absolute"
</Box> top="100%"
<Box> fontSize={11}
<Typography>Uptime Percentage</Typography> color={theme.palette.text.tertiary}
<Typography component="span"> >
{hoveredUptimeData !== null {formatDateWithTz(
? Math.floor( hoveredUptimeData.time,
hoveredUptimeData.uptimePercentage * 10 dateFormat,
) / 10 uiTimezone
: Math.floor(monitor?.periodUptime * 10) / 10} )}
<Typography component="span">%</Typography> </Typography>
</Typography> )}
</Box> </Box>
</Stack> <Box>
<UpBarChart <Typography>Uptime Percentage</Typography>
data={monitor?.aggregateData} <Typography component="span">
type={dateRange} {hoveredUptimeData !== null
onBarHover={setHoveredUptimeData} ? Math.floor(hoveredUptimeData.uptimePercentage * 10) / 10
/> : Math.floor(monitor?.periodUptime * 10) / 10}
</ChartBox> <Typography component="span">%</Typography>
<ChartBox> </Typography>
<Stack> </Box>
<IconBox> </Stack>
<IncidentsIcon /> <UpBarChart
</IconBox> data={monitor?.aggregateData}
<Typography component="h2">Incidents</Typography> type={dateRange}
</Stack> onBarHover={setHoveredUptimeData}
<Box position="relative"> />
<Typography>Total Incidents</Typography> </ChartBox>
<Typography component="span"> <ChartBox>
{hoveredIncidentsData !== null <Stack>
? hoveredIncidentsData.totalIncidents <IconBox>
: monitor?.periodIncidents} <IncidentsIcon />
</Typography> </IconBox>
{hoveredIncidentsData !== null && <Typography component="h2">Incidents</Typography>
hoveredIncidentsData.time !== null && ( </Stack>
<Typography <Box position="relative">
component="h5" <Typography>Total Incidents</Typography>
position="absolute" <Typography component="span">
top="100%" {hoveredIncidentsData !== null
fontSize={11} ? hoveredIncidentsData.totalIncidents
color={theme.palette.text.tertiary} : monitor?.periodIncidents}
> </Typography>
{formatDateWithTz( {hoveredIncidentsData !== null &&
hoveredIncidentsData.time, hoveredIncidentsData.time !== null && (
dateFormat, <Typography
uiTimezone component="h5"
)} position="absolute"
</Typography> top="100%"
)} fontSize={11}
</Box> color={theme.palette.text.tertiary}
<DownBarChart >
data={monitor?.aggregateData} {formatDateWithTz(
type={dateRange} hoveredIncidentsData.time,
onBarHover={setHoveredIncidentsData} dateFormat,
/> uiTimezone
</ChartBox> )}
<ChartBox justifyContent="space-between"> </Typography>
<Stack> )}
<IconBox> </Box>
<AverageResponseIcon /> <DownBarChart
</IconBox> data={monitor?.aggregateData}
<Typography component="h2"> type={dateRange}
Average Response Time onBarHover={setHoveredIncidentsData}
</Typography> />
</Stack> </ChartBox>
<ResponseGaugeChart <ChartBox justifyContent="space-between">
data={[{ response: monitor?.periodAvgResponseTime }]} <Stack>
/> <IconBox>
</ChartBox> <AverageResponseIcon />
<ChartBox sx={{ padding: 0 }}> </IconBox>
<Stack pt={theme.spacing(8)} pl={theme.spacing(8)}> <Typography component="h2">Average Response Time</Typography>
<IconBox> </Stack>
<ResponseTimeIcon /> <ResponseGaugeChart
</IconBox> data={[{ response: monitor?.periodAvgResponseTime }]}
<Typography component="h2">Response Times</Typography> />
</Stack> </ChartBox>
<MonitorDetailsAreaChart <ChartBox sx={{ padding: 0 }}>
checks={[...monitor.checks].reverse()} <Stack
/> pt={theme.spacing(8)}
</ChartBox> pl={theme.spacing(8)}
<ChartBox >
gap={theme.spacing(8)} <IconBox>
sx={{ <ResponseTimeIcon />
flex: "100%", </IconBox>
height: "fit-content", <Typography component="h2">Response Times</Typography>
"& nav": { mt: theme.spacing(12) }, </Stack>
}} <MonitorDetailsAreaChart checks={[...monitor.checks].reverse()} />
> </ChartBox>
<Stack mb={theme.spacing(8)}> <ChartBox
<IconBox> gap={theme.spacing(8)}
<HistoryIcon /> sx={{
</IconBox> flex: "100%",
<Typography height: "fit-content",
component="h2" "& nav": { mt: theme.spacing(12) },
color={theme.palette.text.secondary} }}
> >
History <Stack mb={theme.spacing(8)}>
</Typography> <IconBox>
</Stack> <HistoryIcon />
<PaginationTable </IconBox>
monitorId={monitorId} <Typography
dateRange={dateRange} component="h2"
/> color={theme.palette.text.secondary}
</ChartBox> >
</Stack> History
</Box> </Typography>
</Stack> </Stack>
</> <PaginationTable
)} monitorId={monitorId}
</Box> dateRange={dateRange}
); />
</ChartBox>
</Stack>
</Box>
</Stack>
</>
)}
</Box>
);
}; };
DetailsPage.propTypes = { DetailsPage.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
}; };
export default DetailsPage; export default DetailsPage;
+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,
}, },
}, },
})); }));
@@ -0,0 +1,79 @@
import { useTheme } from "@emotion/react";
import { Box, Stack, Typography } from "@mui/material";
import Search from "../../../../Components/Inputs/Search";
import MemoizedMonitorTable from "../MonitorTable";
import { useState } from "react";
import useDebounce from "../../../../Utils/debounce";
import PropTypes from "prop-types";
const CurrentMonitoring = ({ totalMonitors, monitors, isAdmin }) => {
const theme = useTheme();
const [search, setSearch] = useState("");
const [isSearching, setIsSearching] = useState(false);
const debouncedFilter = useDebounce(search, 500);
const handleSearch = (value) => {
setIsSearching(true);
setSearch(value);
};
return (
<Box
flex={1}
px={theme.spacing(10)}
py={theme.spacing(8)}
border={1}
borderColor={theme.palette.border.light}
borderRadius={theme.shape.borderRadius}
backgroundColor={theme.palette.background.main}
>
<Stack
direction="row"
alignItems="center"
mb={theme.spacing(8)}
>
<Typography
component="h2"
variant="h2"
fontWeight={500}
letterSpacing={-0.2}
>
Actively monitoring
</Typography>
<Box
className="current-monitors-counter"
color={theme.palette.text.primary}
border={1}
borderColor={theme.palette.border.light}
backgroundColor={theme.palette.background.accent}
>
{totalMonitors}
</Box>
<Box
width="25%"
minWidth={150}
ml="auto"
>
<Search
options={monitors}
filteredBy="name"
inputValue={search}
handleInputChange={handleSearch}
/>
</Box>
</Stack>
<MemoizedMonitorTable
isAdmin={isAdmin}
filter={debouncedFilter}
setIsSearching={setIsSearching}
isSearching={isSearching}
/>
</Box>
);
};
CurrentMonitoring.propTypes = {
totalMonitors: PropTypes.number,
monitors: PropTypes.array,
isAdmin: PropTypes.bool,
};
export { CurrentMonitoring };
@@ -0,0 +1,31 @@
import { Skeleton, TableCell, TableRow } from "@mui/material";
const ROWS_NUMBER = 7;
const ROWS_ARRAY = Array.from({ length: ROWS_NUMBER }, (_, i) => i);
const TableBodySkeleton = () => {
return (
<>
{ROWS_ARRAY.map((row) => (
<TableRow key={row}>
<TableCell>
<Skeleton />
</TableCell>
<TableCell>
<Skeleton />
</TableCell>
<TableCell>
<Skeleton />
</TableCell>
<TableCell>
<Skeleton />
</TableCell>
<TableCell>
<Skeleton />
</TableCell>
</TableRow>
))}
</>
);
};
export { TableBodySkeleton };
@@ -1,17 +1,18 @@
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,
CircularProgress,
} 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";
@@ -34,6 +35,7 @@ import RightArrow from "../../../../assets/icons/right-arrow.svg?react";
import SelectorVertical from "../../../../assets/icons/selector-vertical.svg?react"; import SelectorVertical from "../../../../assets/icons/selector-vertical.svg?react";
import ActionsMenu from "../actionsMenu"; import ActionsMenu from "../actionsMenu";
import useUtils from "../../utils"; import useUtils from "../../utils";
import { TableBodySkeleton } from "./Skeleton";
/** /**
* Component for pagination actions (first, previous, next, last). * Component for pagination actions (first, previous, next, last).
@@ -48,386 +50,427 @@ 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, setIsSearching, isSearching }) => {
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 authState = useSelector((state) => state.auth);
const [monitors, setMonitors] = useState([]); const [page, setPage] = useState(0);
const [monitorCount, setMonitorCount] = useState(0); const [monitors, setMonitors] = useState([]);
const authState = useSelector((state) => state.auth); const [monitorCount, setMonitorCount] = useState(0);
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); } catch (error) {
} catch (error) { logger.error(error);
logger.error(error); } finally {
} setIsSearching(false);
}, [authState, page, rowsPerPage, filter, sort, setLoading]); }
}, [authState, page, rowsPerPage, filter, sort, setIsSearching]);
useEffect(() => { useEffect(() => {
fetchPage(); fetchPage();
}, [ }, [
updateTrigger, updateTrigger,
authState, authState,
page, page,
rowsPerPage, rowsPerPage,
filter, filter,
sort, sort,
setLoading, setIsSearching,
fetchPage, 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 (
<> <Box position="relative">
<TableContainer component={Paper}> {isSearching && (
<Table> <>
<TableHead> <Box
<TableRow> width="100%"
<TableCell height="100%"
sx={{ cursor: "pointer" }} position="absolute"
onClick={() => handleSort("name")} sx={{
> backgroundColor: theme.palette.background.main,
<Box> opacity: 0.8,
Host zIndex: 100,
<span }}
style={{ />
visibility: sort.field === "name" ? "visible" : "hidden", <Box
}} height="100%"
> position="absolute"
{sort.order === "asc" ? ( top="20%"
<ArrowUpwardRoundedIcon /> left="50%"
) : ( sx={{
<ArrowDownwardRoundedIcon /> transform: "translateX(-50%)",
)} zIndex: 101,
</span> }}
</Box> >
</TableCell> <CircularProgress
<TableCell sx={{
sx={{ cursor: "pointer" }} color: theme.palette.other.icon,
onClick={() => handleSort("status")} }}
> />
{" "} </Box>
<Box width="max-content"> </>
{" "} )}
Status <TableContainer component={Paper}>
<span <Table>
style={{ <TableHead>
visibility: <TableRow>
sort.field === "status" ? "visible" : "hidden", <TableCell
}} sx={{ cursor: "pointer" }}
> onClick={() => handleSort("name")}
{sort.order === "asc" ? ( >
<ArrowUpwardRoundedIcon /> <Box>
) : ( Host
<ArrowDownwardRoundedIcon /> <span
)} style={{
</span> visibility: sort.field === "name" ? "visible" : "hidden",
</Box> }}
</TableCell> >
<TableCell>Response Time</TableCell> {sort.order === "asc" ? (
<TableCell>Type</TableCell> <ArrowUpwardRoundedIcon />
<TableCell>Actions</TableCell> ) : (
</TableRow> <ArrowDownwardRoundedIcon />
</TableHead> )}
<TableBody> </span>
{monitors.map((monitor) => { </Box>
let uptimePercentage = ""; </TableCell>
let percentageColor = theme.palette.percentage.uptimeExcellent; <TableCell
sx={{ cursor: "pointer" }}
onClick={() => handleSort("status")}
>
{" "}
<Box width="max-content">
{" "}
Status
<span
style={{
visibility: sort.field === "status" ? "visible" : "hidden",
}}
>
{sort.order === "asc" ? (
<ArrowUpwardRoundedIcon />
) : (
<ArrowDownwardRoundedIcon />
)}
</span>
</Box>
</TableCell>
<TableCell>Response Time</TableCell>
<TableCell>Type</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{/* TODO add empty state. Check if is searching, and empty => skeleton. Is empty, not searching => skeleton */}
{monitors.length > 0 ? (
monitors.map((monitor) => {
let uptimePercentage = "";
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> ) : (
</TableContainer> <TableBodySkeleton />
<Stack )}
direction="row" </TableBody>
alignItems="center" </Table>
justifyContent="space-between" </TableContainer>
px={theme.spacing(4)} <Stack
> direction="row"
<Typography px={theme.spacing(2)} variant="body2" sx={{ opacity: 0.7 }}> alignItems="center"
Showing {getRange()} of {monitorCount} monitor(s) justifyContent="space-between"
</Typography> px={theme.spacing(4)}
<TablePagination >
component="div" <Typography
count={monitorCount} px={theme.spacing(2)}
page={page} variant="body2"
onPageChange={handleChangePage} sx={{ opacity: 0.7 }}
rowsPerPage={rowsPerPage} >
rowsPerPageOptions={[5, 10, 15, 25]} Showing {getRange()} of {monitorCount} monitor(s)
onRowsPerPageChange={handleChangeRowsPerPage} </Typography>
ActionsComponent={TablePaginationActions} <TablePagination
labelRowsPerPage="Rows per page" component="div"
labelDisplayedRows={({ page, count }) => count={monitorCount}
`Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}` page={page}
} onPageChange={handleChangePage}
slotProps={{ rowsPerPage={rowsPerPage}
select: { rowsPerPageOptions={[5, 10, 15, 25]}
MenuProps: { onRowsPerPageChange={handleChangeRowsPerPage}
keepMounted: true, ActionsComponent={TablePaginationActions}
disableScrollLock: true, labelRowsPerPage="Rows per page"
PaperProps: { labelDisplayedRows={({ page, count }) =>
className: "pagination-dropdown", `Page ${page + 1} of ${Math.max(0, Math.ceil(count / rowsPerPage))}`
sx: { }
mt: 0, slotProps={{
mb: theme.spacing(2), select: {
}, MenuProps: {
}, keepMounted: true,
transformOrigin: { vertical: "bottom", horizontal: "left" }, disableScrollLock: true,
anchorOrigin: { vertical: "top", horizontal: "left" }, PaperProps: {
sx: { mt: theme.spacing(-2) }, className: "pagination-dropdown",
}, sx: {
inputProps: { id: "pagination-dropdown" }, mt: 0,
IconComponent: SelectorVertical, mb: theme.spacing(2),
sx: { },
ml: theme.spacing(4), },
mr: theme.spacing(12), transformOrigin: { vertical: "bottom", horizontal: "left" },
minWidth: theme.spacing(20), anchorOrigin: { vertical: "top", horizontal: "left" },
textAlign: "left", sx: { mt: theme.spacing(-2) },
"&.Mui-focused > div": { },
backgroundColor: theme.palette.background.main, inputProps: { id: "pagination-dropdown" },
}, IconComponent: SelectorVertical,
}, sx: {
}, ml: theme.spacing(4),
}} mr: theme.spacing(12),
sx={{ minWidth: theme.spacing(20),
mt: theme.spacing(6), textAlign: "left",
color: theme.palette.text.secondary, "&.Mui-focused > div": {
"& svg path": { backgroundColor: theme.palette.background.main,
stroke: theme.palette.text.tertiary, },
strokeWidth: 1.3, },
}, },
"& .MuiSelect-select": { }}
border: 1, sx={{
borderColor: theme.palette.border.light, mt: theme.spacing(6),
borderRadius: theme.shape.borderRadius, color: theme.palette.text.secondary,
}, "& svg path": {
}} stroke: theme.palette.text.tertiary,
/> strokeWidth: 1.3,
</Stack> },
</> "& .MuiSelect-select": {
); border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
},
}}
/>
</Stack>
</Box>
);
}; };
MonitorTable.propTypes = { MonitorTable.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
filter: PropTypes.string, filter: PropTypes.string,
setLoading: PropTypes.func, setIsSearching: PropTypes.func,
isSearching: PropTypes.bool,
}; };
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;
+201 -222
View File
@@ -3,244 +3,223 @@ import { useSelector, useDispatch } from "react-redux";
import { useTheme } from "@emotion/react"; 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 { IconButton, Menu, MenuItem } from "@mui/material";
import { import {
Button, deleteUptimeMonitor,
IconButton, pauseUptimeMonitor,
Menu, getUptimeMonitorsByTeamId,
MenuItem,
Modal,
Stack,
Typography,
} from "@mui/material";
import {
deleteUptimeMonitor,
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";
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 { 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 openMenu = (event, id, url) => { const handlePause = async () => {
event.preventDefault(); try {
event.stopPropagation(); const action = await dispatch(
setAnchorEl(event.currentTarget); pauseUptimeMonitor({ authToken, monitorId: monitor._id })
setActions({ id: id, url: url }); );
}; if (pauseUptimeMonitor.fulfilled.match(action)) {
updateCallback();
const state = action?.payload?.data.isActive === false ? "paused" : "resumed";
createToast({ body: `Monitor ${state} successfully.` });
} else {
throw new Error(action?.error?.message ?? "Failed to pause monitor.");
}
} catch (error) {
logger.error("Error pausing monitor:", monitor._id, error);
createToast({ body: "Failed to pause monitor." });
}
};
const openRemove = (e) => { const openMenu = (event, id, url) => {
closeMenu(e); event.preventDefault();
setIsOpen(true); event.stopPropagation();
}; setAnchorEl(event.currentTarget);
setActions({ id: id, url: url });
};
const closeMenu = (e) => { const openRemove = (e) => {
e.stopPropagation(); closeMenu(e);
setAnchorEl(null); setIsOpen(true);
}; };
const navigate = useNavigate(); const closeMenu = (e) => {
return ( e.stopPropagation();
<> setAnchorEl(null);
<IconButton };
aria-label="monitor actions"
onClick={(event) => {
event.stopPropagation();
openMenu(
event,
monitor._id,
monitor.type === "ping" ? null : monitor.url
);
}}
sx={{
"&:focus": {
outline: "none",
},
"& svg path": {
stroke: theme.palette.other.icon,
},
}}
>
<Settings />
</IconButton>
<Menu const navigate = useNavigate();
className="actions-menu" return (
anchorEl={anchorEl} <>
open={Boolean(anchorEl)} <IconButton
onClose={(e) => closeMenu(e)} aria-label="monitor actions"
disableScrollLock onClick={(event) => {
slotProps={{ event.stopPropagation();
paper: { openMenu(event, monitor._id, monitor.type === "ping" ? null : monitor.url);
sx: { }}
"& ul": { p: theme.spacing(2.5) }, sx={{
"& li": { m: 0 }, "&:focus": {
"& li:last-of-type": { outline: "none",
color: theme.palette.error.text, },
}, "& svg path": {
}, stroke: theme.palette.other.icon,
}, },
}} }}
> >
{actions.url !== null ? ( <Settings />
<MenuItem </IconButton>
onClick={(e) => {
closeMenu(e);
e.stopPropagation();
window.open(actions.url, "_blank", "noreferrer");
}}
>
Open site
</MenuItem>
) : (
""
)}
<MenuItem
onClick={(e) => {
e.stopPropagation();
navigate(`/monitors/${actions.id}`);
}}
>
Details
</MenuItem>
{/* TODO - pass monitor id to Incidents page */}
<MenuItem
onClick={(e) => {
e.stopPropagation();
navigate(`/incidents/${actions.id}`);
}}
>
Incidents
</MenuItem>
{isAdmin && (
<MenuItem
onClick={(e) => {
e.stopPropagation();
navigate(`/monitors/configure/${actions.id}`); <Menu
}} className="actions-menu"
> anchorEl={anchorEl}
Configure open={Boolean(anchorEl)}
</MenuItem> onClose={(e) => closeMenu(e)}
)} disableScrollLock
{isAdmin && ( slotProps={{
<MenuItem paper: {
onClick={(e) => { sx: {
e.stopPropagation(); "& ul": { p: theme.spacing(2.5) },
navigate(`/monitors/create/${actions.id}`); "& li": { m: 0 },
}} "& li:last-of-type": {
> color: theme.palette.error.text,
Clone },
</MenuItem> },
)} },
{isAdmin && ( }}
<MenuItem >
onClick={(e) => { {actions.url !== null ? (
e.stopPropagation(); <MenuItem
openRemove(e); onClick={(e) => {
}} closeMenu(e);
> e.stopPropagation();
Remove window.open(actions.url, "_blank", "noreferrer");
</MenuItem> }}
)} >
</Menu> Open site
<Modal </MenuItem>
aria-labelledby="modal-delete-monitor" ) : (
aria-describedby="delete-monitor-confirmation" ""
open={isOpen} )}
onClose={(e) => { <MenuItem
e.stopPropagation(); onClick={(e) => {
setIsOpen(false); e.stopPropagation();
}} navigate(`/monitors/${actions.id}`);
> }}
<Stack >
gap={theme.spacing(2)} Details
sx={{ </MenuItem>
position: "absolute", {/* TODO - pass monitor id to Incidents page */}
top: "50%", <MenuItem
left: "50%", onClick={(e) => {
transform: "translate(-50%, -50%)", e.stopPropagation();
width: 400, navigate(`/incidents/${actions.id}`);
bgcolor: theme.palette.background.main, }}
border: 1, >
borderColor: theme.palette.border.light, Incidents
borderRadius: theme.shape.borderRadius, </MenuItem>
boxShadow: 24, {isAdmin && (
p: theme.spacing(15), <MenuItem
"&:focus": { onClick={(e) => {
outline: "none", e.stopPropagation();
},
}} navigate(`/monitors/configure/${actions.id}`);
> }}
<Typography id="modal-delete-monitor" component="h2" variant="h2"> >
Do you really want to delete this monitor? Configure
</Typography> </MenuItem>
<Typography id="delete-monitor-confirmation" variant="body1"> )}
Once deleted, this monitor cannot be retrieved. {isAdmin && (
</Typography> <MenuItem
<Stack onClick={(e) => {
direction="row" e.stopPropagation();
gap={theme.spacing(4)} navigate(`/monitors/create/${actions.id}`);
mt={theme.spacing(12)} }}
justifyContent="flex-end" >
> Clone
<Button </MenuItem>
variant="text" )}
color="info" {isAdmin && (
onClick={(e) => { <MenuItem
e.stopPropagation(); onClick={(e) => {
setIsOpen(false); e.stopPropagation();
}} handlePause(e);
> }}
Cancel >
</Button> {monitor?.isActive === true ? "Pause" : "Resume"}
<Button </MenuItem>
variant="contained" )}
color="error" {isAdmin && (
onClick={(e) => { <MenuItem
e.stopPropagation(e); onClick={(e) => {
handleRemove(e); e.stopPropagation();
}} openRemove(e);
> }}
Delete >
</Button> Remove
</Stack> </MenuItem>
</Stack> )}
</Modal> </Menu>
</> <Dialog
); open={isOpen}
theme={theme}
title="Do you really want to delete this monitor?"
description="Once deleted, this monitor cannot be retrieved."
/* Do we need stop propagation? */
onCancel={(e) => {
e.stopPropagation();
setIsOpen(false);
}}
confirmationButtonLabel="Delete"
/* Do we need stop propagation? */
onConfirm={(e) => {
e.stopPropagation();
handleRemove(e);
}}
isLoading={isLoading}
modelTitle="modal-delete-monitor"
modelDescription="delete-monitor-confirmation"
/>
</>
);
}; };
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,
}).isRequired, isActive: PropTypes.bool,
isAdmin: PropTypes.bool, }).isRequired,
updateCallback: PropTypes.func, isAdmin: PropTypes.bool,
updateCallback: PropTypes.func,
}; };
export default ActionsMenu; export default ActionsMenu;
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff. Show more