Refactor Create PageSpeed

This commit is contained in:
Alex Holliday committed 2024-12-06 14:25:11 +08:00
1 parent 958904e6d5
commit f148e2d9ad
1 file changed
+142 -171
@@ -1,42 +1,52 @@
// React, Redux, Router
import { useNavigate, useParams } from "react-router-dom";
import { useEffect } from "react";
import { useState } from "react"; import { useState } from "react";
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";
// Utility and Network
import { logger } from "../../../Utils/Logger";
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { useNavigate } from "react-router-dom";
import { useTheme } from "@emotion/react";
import { import {
createPageSpeed, createPageSpeed,
checkEndpointResolution, checkEndpointResolution,
} from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice"; } from "../../../Features/PageSpeedMonitor/pageSpeedMonitorSlice";
import { createToast } from "../../../Utils/toastUtils"; import { parseDomainName } from "../../../Utils/monitorUtils";
import { logger } from "../../../Utils/Logger";
import { ConfigBox } from "../../Monitors/styled"; // MUI
import Radio from "../../../Components/Inputs/Radio"; 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";
import TextInput from "../../../Components/Inputs/TextInput"; import TextInput from "../../../Components/Inputs/TextInput";
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments"; import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import Select from "../../../Components/Inputs/Select"; import { ConfigBox } from "../../Monitors/styled";
import { createToast } from "../../../Utils/toastUtils";
import Radio from "../../../Components/Inputs/Radio";
import Checkbox from "../../../Components/Inputs/Checkbox"; import Checkbox from "../../../Components/Inputs/Checkbox";
import Breadcrumbs from "../../../Components/Breadcrumbs"; import Select from "../../../Components/Inputs/Select";
import { parseDomainName } from "../../../Utils/monitorUtils";
import "./index.css";
const CreatePageSpeed = () => { const CreatePageSpeed = () => {
const MS_PER_MINUTE = 60000; const MS_PER_MINUTE = 60000;
const { user, authToken } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
const dispatch = useDispatch();
const navigate = useNavigate();
const theme = useTheme();
const idMap = { const CRUMBS = [
"monitor-url": "url", { name: "pagespeed", path: "/pagespeed" },
"monitor-name": "name", { name: "create", path: `/pagespeed/create` },
"monitor-checks-http": "type", ];
"monitor-checks-ping": "type",
"notify-email-default": "notification-email",
};
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" },
];
// State
const [monitor, setMonitor] = useState({ const [monitor, setMonitor] = useState({
url: "", url: "",
name: "", name: "",
@@ -44,71 +54,20 @@ const CreatePageSpeed = () => {
notifications: [], notifications: [],
interval: 3, interval: 3,
}); });
const [https, setHttps] = useState(true); const [https, setHttps] = useState(true);
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const { user, authToken } = useSelector((state) => state.auth);
const { isLoading } = useSelector((state) => state.pageSpeedMonitors);
const handleChange = (event, name) => { // Setup
const { value, id } = event.target; const dispatch = useDispatch();
if (!name) name = idMap[id]; const navigate = useNavigate();
const theme = useTheme();
if (name.includes("notification-")) {
name = name.replace("notification-", "");
let hasNotif = monitor.notifications.some(
(notification) => notification.type === name
);
setMonitor((prev) => {
const notifs = [...prev.notifications];
if (hasNotif) {
return {
...prev,
notifications: notifs.filter((notif) => notif.type !== name),
};
} else {
return {
...prev,
notifications: [
...notifs,
name === "email"
? { type: name, address: value }
: // TODO - phone number
{ type: name, phone: value },
],
};
}
});
} else {
setMonitor((prev) => ({
...prev,
[name]: value,
}));
const { error } = monitorValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
const updatedErrors = { ...prev };
if (error) updatedErrors[name] = error.details[0].message;
else delete updatedErrors[name];
return updatedErrors;
});
}
};
const onUrlBlur = (event) => {
const { value } = event.target;
if (monitor.name === "") {
setMonitor((prev) => ({
...prev,
name: parseDomainName(value),
}));
}
};
// Handlers
const handleCreateMonitor = async (event) => { const handleCreateMonitor = async (event) => {
event.preventDefault(); event.preventDefault();
//obj to submit
let form = { let form = {
url: `http${https ? "s" : ""}://` + monitor.url, url: `http${https ? "s" : ""}://` + monitor.url,
name: monitor.name === "" ? monitor.url : monitor.name, name: monitor.name === "" ? monitor.url : monitor.name,
@@ -126,46 +85,98 @@ const CreatePageSpeed = () => {
newErrors[err.path[0]] = err.message; newErrors[err.path[0]] = err.message;
}); });
setErrors(newErrors); setErrors(newErrors);
createToast({ body: "Error validation data." }); createToast({ body: "Please check the form for errors." });
} else { 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 = { const checkEndpointAction = await dispatch(
...form, checkEndpointResolution({ authToken, monitorURL: form.url })
description: form.name, );
teamId: user.teamId,
userId: user._id, if (checkEndpointAction.meta.requestStatus === "rejected") {
notifications: monitor.notifications, createToast({
}; body: "The endpoint you entered doesn't resolve. Check the URL again.",
const action = await dispatch(createPageSpeed({ authToken, monitor: form })); });
if (action.meta.requestStatus === "fulfilled") { setErrors({ url: "The entered URL is not reachable." });
createToast({ body: "Monitor created successfully!" }); return;
navigate("/pagespeed"); }
} else {
createToast({ body: "Failed to create monitor." }); form = {
} ...form,
description: form.name,
teamId: user.teamId,
userId: user._id,
notifications: monitor.notifications,
};
const action = await dispatch(createPageSpeed({ authToken, monitor: form }));
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Monitor created successfully!" });
navigate("/pagespeed");
} else {
createToast({ body: "Failed to create monitor." });
}
};
const handleChange = (event, formItemName) => {
const { value } = event.target;
setMonitor({
...monitor,
[formItemName]: value,
});
const { error } = monitorValidation.validate(
{ [formItemName]: value },
{ abortEarly: false }
);
setErrors((prev) => ({
...prev,
...(error
? { [formItemName]: error.details[0].message }
: { [formItemName]: undefined }),
}));
};
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;
}
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, formItemName) => {
if (formItemName === "url") {
const { value } = event.target;
if (monitor.name !== "") {
return;
}
setMonitor((prev) => ({
...prev,
name: parseDomainName(value),
}));
} }
}; };
//select values
const frequencies = [
{ _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" },
];
return ( return (
<Box <Box
className="create-monitor" className="create-monitor"
@@ -175,12 +186,7 @@ const CreatePageSpeed = () => {
}, },
}} }}
> >
<Breadcrumbs <Breadcrumbs list={CRUMBS} />
list={[
{ name: "pagespeed", path: "/pagespeed" },
{ name: "create", path: `/pagespeed/create` },
]}
/>
<Stack <Stack
component="form" component="form"
className="create-monitor-form" className="create-monitor-form"
@@ -206,7 +212,7 @@ const CreatePageSpeed = () => {
fontWeight="inherit" fontWeight="inherit"
color={theme.palette.text.secondary} color={theme.palette.text.secondary}
> >
pagespeed monitor PageSpeed monitor
</Typography> </Typography>
</Typography> </Typography>
<ConfigBox> <ConfigBox>
@@ -224,8 +230,8 @@ const CreatePageSpeed = () => {
startAdornment={<HttpAdornment https={https} />} startAdornment={<HttpAdornment https={https} />}
placeholder="google.com" placeholder="google.com"
value={monitor.url} value={monitor.url}
onChange={handleChange} onChange={(event) => handleChange(event, "url")}
onBlur={onUrlBlur} onBlur={(event) => handleBlur(event, "url")}
error={errors["url"] ? true : false} error={errors["url"] ? true : false}
helperText={errors["url"]} helperText={errors["url"]}
/> />
@@ -236,7 +242,7 @@ const CreatePageSpeed = () => {
isOptional={true} isOptional={true}
placeholder="Google" placeholder="Google"
value={monitor.name} value={monitor.name}
onChange={handleChange} onChange={(event) => handleChange(event, "name")}
error={errors["name"] ? true : false} error={errors["name"] ? true : false}
helperText={errors["name"]} helperText={errors["name"]}
/> />
@@ -253,8 +259,8 @@ const CreatePageSpeed = () => {
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
<Radio <Radio
id="monitor-checks-http" id="monitor-checks-http"
title="Website monitoring" title="PageSpeed"
desc="Use HTTP(s) to monitor your website or API endpoint." desc="Use the Lighthouse PageSpeed API to monitor your website"
size="small" size="small"
value="http" value="http"
checked={monitor.type === "pagespeed"} checked={monitor.type === "pagespeed"}
@@ -269,8 +275,8 @@ const CreatePageSpeed = () => {
HTTPS HTTPS
</Button> </Button>
<Button <Button
variant="group" variant="group" // Why does this work?
filled={(!https).toString()} filled={(!https).toString()} // There's nothing in the docs about this either
onClick={() => setHttps(false)} onClick={() => setHttps(false)}
> >
HTTP HTTP
@@ -301,14 +307,6 @@ const CreatePageSpeed = () => {
</Box> </Box>
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
<Typography component="p">When there is a new incident,</Typography> <Typography component="p">When there is a new incident,</Typography>
<Checkbox
id="notify-sms"
label="Notify via SMS (coming soon)"
isChecked={false}
value=""
onChange={() => logger.warn("disabled")}
isDisabled={true}
/>
<Checkbox <Checkbox
id="notify-email-default" id="notify-email-default"
label={`Notify via email (to ${user.email})`} label={`Notify via email (to ${user.email})`}
@@ -316,34 +314,8 @@ const CreatePageSpeed = () => {
(notification) => notification.type === "email" (notification) => notification.type === "email"
)} )}
value={user?.email} value={user?.email}
onChange={(event) => handleChange(event)} onChange={(event) => handleNotifications(event, "email")}
/> />
<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)}>
<TextInput
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> </Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
@@ -356,7 +328,7 @@ const CreatePageSpeed = () => {
label="Check frequency" label="Check frequency"
value={monitor.interval || 3} value={monitor.interval || 3}
onChange={(event) => handleChange(event, "interval")} onChange={(event) => handleChange(event, "interval")}
items={frequencies} items={SELECT_VALUES}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -368,7 +340,7 @@ const CreatePageSpeed = () => {
variant="contained" variant="contained"
color="primary" color="primary"
onClick={handleCreateMonitor} onClick={handleCreateMonitor}
disabled={Object.keys(errors).length !== 0 && true} disabled={!Object.values(errors).every((value) => value === undefined)}
loading={isLoading} loading={isLoading}
> >
Create monitor Create monitor
@@ -378,5 +350,4 @@ const CreatePageSpeed = () => {
</Box> </Box>
); );
}; };
export default CreatePageSpeed; export default CreatePageSpeed;