Files
Checkmate/Client/src/Pages/PageSpeed/CreatePageSpeed/index.jsx
T

353 lines
9.0 KiB
React
Raw Normal View History

2024-12-06 14:25:11 +08:00
// React, Redux, Router
import { useNavigate } from "react-router-dom";
2024-07-30 13:40:31 -04:00
import { useState } from "react";
2024-09-05 14:09:50 -07:00
import { useSelector, useDispatch } from "react-redux";
2024-12-06 14:25:11 +08:00
// Utility and Network
2024-09-05 14:09:50 -07:00
import { monitorValidation } from "../../../Validation/validation";
2024-11-10 17:00:13 -05:00
import {
createPageSpeed,
checkEndpointResolution,
} from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice";
2024-12-06 14:25:11 +08:00
import { parseDomainName } from "../../../Utils/monitorUtils";
// MUI
import { useTheme } from "@emotion/react";
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
2024-11-26 14:32:22 +08:00
import TextInput from "../../../Components/Inputs/TextInput";
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
2024-12-12 10:23:36 -05:00
import { ConfigBox } from "../../Uptime/styled";
2024-12-06 14:25:11 +08:00
import { createToast } from "../../../Utils/toastUtils";
import Radio from "../../../Components/Inputs/Radio";
2024-07-28 16:51:47 -04:00
import Checkbox from "../../../Components/Inputs/Checkbox";
2024-12-06 14:25:11 +08:00
import Select from "../../../Components/Inputs/Select";
2024-07-30 13:40:31 -04:00
const MS_PER_MINUTE = 60000;
const CRUMBS = [
{ name: "pagespeed", path: "/pagespeed" },
{ name: "create", path: `/pagespeed/create` },
];
2024-07-28 16:51:47 -04:00
const SELECT_VALUES = [
{ _id: 3, name: "3 minutes" },
{ _id: 5, name: "5 minutes" },
{ _id: 10, name: "10 minutes" },
{ _id: 20, name: "20 minutes" },
{ _id: 60, name: "1 hour" },
{ _id: 1440, name: "1 day" },
{ _id: 10080, name: "1 week" },
];
2024-07-28 16:51:47 -04:00
const CreatePageSpeed = () => {
2024-12-06 14:25:11 +08:00
// State
const [monitor, setMonitor] = useState({
url: "",
name: "",
type: "pagespeed",
notifications: [],
interval: 3,
});
2024-12-06 14:25:11 +08:00
const [https, setHttps] = useState(true);
const [errors, setErrors] = useState({});
2024-12-06 14:25:11 +08:00
const { user, authToken } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
2024-12-06 14:25:11 +08:00
// Setup
const dispatch = useDispatch();
const navigate = useNavigate();
const theme = useTheme();
2024-11-27 15:48:06 +08:00
2024-12-06 14:25:11 +08:00
// Handlers
const handleCreateMonitor = async (event) => {
event.preventDefault();
let form = {
url: `http${https ? "s" : ""}://` + monitor.url,
name: monitor.name === "" ? monitor.url : monitor.name,
type: monitor.type,
interval: monitor.interval * MS_PER_MINUTE,
};
2024-07-30 13:40:31 -04:00
const { error } = monitorValidation.validate(form, {
abortEarly: false,
});
2024-07-30 13:40:31 -04:00
2024-11-10 17:00:13 -05:00
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
2024-12-06 14:25:11 +08:00
createToast({ body: "Please check the form for errors." });
return;
}
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;
}
form = {
...form,
description: form.name,
teamId: user.teamId,
userId: user._id,
notifications: monitor.notifications,
};
const action = await dispatch(createPageSpeed({ authToken, monitor: form }));
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" });
navigate("/pagespeed");
2024-11-10 17:00:13 -05:00
} else {
2024-12-06 14:25:11 +08:00
createToast({ body: "Failed to create monitor." });
}
};
const handleChange = (event) => {
const { value, name } = event.target;
2024-12-06 14:25:11 +08:00
setMonitor({
...monitor,
[name]: value,
2024-12-06 14:25:11 +08:00
});
const { error } = monitorValidation.validate(
{ [name]: value },
2024-12-06 14:25:11 +08:00
{ abortEarly: false }
);
setErrors((prev) => ({
...prev,
...(error ? { [name]: error.details[0].message } : { [name]: undefined }),
2024-12-06 14:25:11 +08:00
}));
};
const handleNotifications = (event, type) => {
const { value } = event.target;
let notifications = [...monitor.notifications];
const notificationExists = notifications.some((notification) => {
if (notification.type === type && notification.address === value) {
return true;
2024-11-10 17:00:13 -05:00
}
2024-12-06 14:25:11 +08:00
return false;
});
if (notificationExists) {
notifications = notifications.filter((notification) => {
if (notification.type === type && notification.address === value) {
return false;
}
return true;
});
} else {
notifications.push({ type, address: value });
}
setMonitor((prev) => ({
...prev,
notifications,
}));
};
const handleBlur = (event) => {
const { name } = event.target;
if (name === "url") {
2024-12-06 14:25:11 +08:00
const { value } = event.target;
if (monitor.name !== "") {
return;
2024-11-10 17:00:13 -05:00
}
2024-12-06 14:25:11 +08:00
setMonitor((prev) => ({
...prev,
name: parseDomainName(value),
}));
2024-11-10 17:00:13 -05:00
}
};
2024-07-30 13:40:31 -04:00
2024-11-10 17:00:13 -05:00
return (
<Box
className="create-monitor"
sx={{
"& h1": {
color: theme.palette.text.primary,
},
}}
>
2024-12-06 14:25:11 +08:00
<Breadcrumbs list={CRUMBS} />
2024-11-10 17:00:13 -05:00
<Stack
component="form"
className="create-monitor-form"
onSubmit={handleCreateMonitor}
noValidate
spellCheck="false"
gap={theme.spacing(12)}
mt={theme.spacing(6)}
>
<Typography
component="h1"
variant="h1"
>
<Typography
component="span"
fontSize="inherit"
>
Create your{" "}
</Typography>
<Typography
component="span"
fontSize="inherit"
fontWeight="inherit"
color={theme.palette.text.secondary}
>
2024-12-06 14:25:11 +08:00
PageSpeed monitor
2024-11-10 17:00:13 -05:00
</Typography>
</Typography>
<ConfigBox>
<Box>
<Typography component="h2">General settings</Typography>
<Typography component="p">
Here you can select the URL of the host, together with the type of monitor.
</Typography>
</Box>
<Stack gap={theme.spacing(15)}>
2024-11-26 14:32:22 +08:00
<TextInput
2024-11-10 17:00:13 -05:00
type={"url"}
name="url"
2024-11-10 17:00:13 -05:00
id="monitor-url"
label="URL to monitor"
2024-11-26 14:32:22 +08:00
startAdornment={<HttpAdornment https={https} />}
2024-11-10 17:00:13 -05:00
placeholder="google.com"
value={monitor.url}
onChange={handleChange}
onBlur={handleBlur}
2024-11-26 14:32:22 +08:00
error={errors["url"] ? true : false}
helperText={errors["url"]}
2024-11-10 17:00:13 -05:00
/>
2024-11-26 14:32:22 +08:00
<TextInput
2024-11-10 17:00:13 -05:00
type="text"
id="monitor-name"
name="name"
2024-11-10 17:00:13 -05:00
label="Display name"
isOptional={true}
placeholder="Google"
value={monitor.name}
onChange={handleChange}
2024-11-26 14:32:22 +08:00
error={errors["name"] ? true : false}
helperText={errors["name"]}
2024-11-10 17:00:13 -05:00
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Checks to perform</Typography>
<Typography component="p">
You can always add or remove checks after adding your site.
</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
<Stack gap={theme.spacing(6)}>
<Radio
id="monitor-checks-http"
2024-12-06 14:25:11 +08:00
title="PageSpeed"
desc="Use the Lighthouse PageSpeed API to monitor your website"
2024-11-10 17:00:13 -05:00
size="small"
value="http"
checked={monitor.type === "pagespeed"}
/>
<ButtonGroup sx={{ ml: "32px" }}>
<Button
variant="group"
filled={https.toString()}
onClick={() => setHttps(true)}
>
HTTPS
</Button>
<Button
2024-12-06 14:25:11 +08:00
variant="group" // Why does this work?
filled={(!https).toString()} // There's nothing in the docs about this either
2024-11-10 17:00:13 -05:00
onClick={() => setHttps(false)}
>
HTTP
</Button>
</ButtonGroup>
</Stack>
{errors["type"] ? (
<Box className="error-container">
<Typography
component="p"
className="input-error"
color={theme.palette.error.contrastText}
>
{errors["type"]}
</Typography>
</Box>
) : (
""
)}
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Incident notifications</Typography>
<Typography component="p">
When there is an incident, notify users.
</Typography>
</Box>
<Stack gap={theme.spacing(6)}>
<Typography component="p">When there is a new incident,</Typography>
<Checkbox
id="notify-email-default"
label={`Notify via email (to ${user.email})`}
isChecked={monitor.notifications.some(
(notification) => notification.type === "email"
)}
value={user?.email}
2024-12-06 14:25:11 +08:00
onChange={(event) => handleNotifications(event, "email")}
2024-11-10 17:00:13 -05:00
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Advanced settings</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
<Select
id="monitor-interval"
name="interval"
2024-11-10 17:00:13 -05:00
label="Check frequency"
value={monitor.interval || 3}
onChange={handleChange}
2024-12-06 14:25:11 +08:00
items={SELECT_VALUES}
2024-11-10 17:00:13 -05:00
/>
</Stack>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton
variant="contained"
color="primary"
onClick={handleCreateMonitor}
2024-12-06 14:25:11 +08:00
disabled={!Object.values(errors).every((value) => value === undefined)}
2024-11-10 17:00:13 -05:00
loading={isLoading}
>
Create monitor
</LoadingButton>
</Stack>
</Stack>
</Box>
);
2024-07-28 16:51:47 -04:00
};
export default CreatePageSpeed;