Files
Checkmate/client/src/Pages/PageSpeed/Create/index.jsx
T

514 lines
13 KiB
React
Raw Normal View History

// Components
import { Box, Stack, Tooltip, Typography, Button, ButtonGroup } from "@mui/material";
2025-09-27 14:54:55 -07:00
import ConfigBox from "@/Components/v1/ConfigBox/index.jsx";
import Select from "@/Components/v1/Inputs/Select/index.jsx";
import TextInput from "@/Components/v1/Inputs/TextInput/index.jsx";
import Icon from "@/Components/v1/Icon";
2025-09-27 14:54:55 -07:00
import Breadcrumbs from "@/Components/v1/Breadcrumbs/index.jsx";
import PulseDot from "@/Components/v1/Animated/PulseDot.jsx";
2025-09-25 10:11:41 -07:00
import SkeletonLayout from "./skeleton.jsx";
2025-09-27 14:54:55 -07:00
import NotificationsConfig from "@/Components/v1/NotificationConfig/index.jsx";
import Dialog from "@/Components/v1/Dialog/index.jsx";
import { HttpAdornment } from "@/Components/v1/Inputs/TextInput/Adornments/index.jsx";
import Radio from "@/Components/v1/Inputs/Radio/index.jsx";
// Utils
import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
2026-01-12 23:57:39 +00:00
import { monitorValidation } from "../../../Validation/validation.js";
import { parseDomainName } from "../../../Utils/monitorUtils.js";
import { useTranslation } from "react-i18next";
2026-01-12 23:57:39 +00:00
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications.js";
import { useTheme } from "@emotion/react";
2026-01-12 23:57:39 +00:00
import { createToast } from "../../../Utils/toastUtils.jsx";
import { useParams } from "react-router";
2026-01-12 23:57:39 +00:00
import { useMonitorUtils } from "../../../Hooks/useMonitorUtils.js";
import {
2025-07-08 19:13:40 -04:00
useCreateMonitor,
useFetchMonitorById,
useDeleteMonitor,
useUpdateMonitor,
usePauseMonitor,
2026-01-12 23:57:39 +00:00
} from "../../../Hooks/monitorHooks.js";
const PageSpeedSetup = () => {
2025-07-08 19:13:40 -04:00
const { monitorId } = useParams();
const isCreate = typeof monitorId === "undefined";
2025-07-08 19:13:40 -04:00
const CRUMBS = [
{ name: "pagespeed", path: "/pagespeed" },
...(isCreate
? [{ name: "create", path: `/pagespeed/create` }]
: [
2025-07-08 19:13:40 -04:00
{ name: "details", path: `/pagespeed/${monitorId}` },
{ name: "configure", path: `/pagespeed/configure/${monitorId}` },
]),
2025-07-08 19:13:40 -04:00
];
2025-07-08 19:13:40 -04:00
// States
const [monitor, setMonitor] = useState(
isCreate
? {
2025-07-08 19:13:40 -04:00
url: "",
name: "",
type: "pagespeed",
notifications: [],
interval: 180000,
}
: {}
2025-07-08 19:13:40 -04:00
);
const [https, setHttps] = useState(true);
const [errors, setErrors] = useState({});
const [isOpen, setIsOpen] = useState(false);
const [updateTrigger, setUpdateTrigger] = useState(false);
2025-07-08 19:13:40 -04:00
// Setup
const { t } = useTranslation();
const theme = useTheme();
// Constants
const MS_PER_MINUTE = 60000;
const FREQUENCIES = [
{ _id: 3, name: t("time.threeMinutes") },
{ _id: 5, name: t("time.fiveMinutes") },
{ _id: 10, name: t("time.tenMinutes") },
{ _id: 20, name: t("time.twentyMinutes") },
{ _id: 60, name: t("time.oneHour") },
{ _id: 1440, name: t("time.oneDay") },
{ _id: 10080, name: t("time.oneWeek") },
];
const { user } = useSelector((state) => state.auth);
2025-07-08 19:13:40 -04:00
const { statusColor, pagespeedStatusMsg, determineState } = useMonitorUtils();
const [notifications, notificationsAreLoading, notificationsError] =
useGetNotificationsByTeamId();
2025-07-08 19:13:40 -04:00
// Hooks for API actions
const [isLoading] = useFetchMonitorById({ monitorId, setMonitor, updateTrigger });
2025-07-08 19:13:40 -04:00
const [createMonitor, isCreating] = useCreateMonitor();
const [deleteMonitor, isDeleting] = useDeleteMonitor();
const [updateMonitor, isUpdating] = useUpdateMonitor();
const [pauseMonitor, isPausing] = usePauseMonitor();
2025-07-08 19:13:40 -04:00
// Handlers
const onSubmit = async (event) => {
event.preventDefault();
if (isCreate) {
2025-07-08 19:13:40 -04:00
let form = {
url: `http${https ? "s" : ""}://` + monitor.url,
name: monitor.name === "" ? monitor.url : monitor.name,
type: monitor.type,
interval: monitor.interval,
};
2025-07-08 19:13:40 -04:00
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: t("checkFormError") });
2025-07-08 19:13:40 -04:00
return;
}
2025-07-08 19:13:40 -04:00
form = {
...form,
description: form.name,
notifications: monitor.notifications,
};
await createMonitor({ monitor: form, redirect: "/pagespeed" });
} else {
const monitorParams = {
url: monitor.url,
name: monitor.name === "" ? monitor.url : monitor.name,
type: monitor.type,
interval: monitor.interval,
};
const { error } = monitorValidation.validate(monitorParams, { abortEarly: false });
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
createToast({ body: t("checkFormError") });
return;
}
await updateMonitor({ monitor, redirect: "/pagespeed" });
2025-07-08 19:13:40 -04:00
}
};
2025-07-08 19:13:40 -04:00
const handleChange = (event) => {
let { value, name } = event.target;
2025-07-08 19:13:40 -04:00
if (name === "interval") {
value = value * MS_PER_MINUTE;
}
2025-07-08 19:13:40 -04:00
setMonitor({
...monitor,
[name]: value,
});
2025-07-08 19:13:40 -04:00
const { error } = monitorValidation.validate(
2025-08-15 16:40:21 -07:00
{ [name]: value, type: monitor.type },
2025-07-08 19:13:40 -04:00
{ abortEarly: false }
);
setErrors((prev) => ({
...prev,
...(error ? { [name]: error.details[0].message } : { [name]: undefined }),
}));
};
2025-07-08 19:13:40 -04:00
const handleBlur = (event) => {
const { name, value } = event.target;
if (name === "url" && monitor.name === "") {
setMonitor((prev) => ({ ...prev, name: parseDomainName(value) }));
}
};
const triggerUpdate = () => {
setUpdateTrigger(!updateTrigger);
};
2025-07-08 19:13:40 -04:00
const handlePause = async () => {
await pauseMonitor({ monitorId, triggerUpdate });
};
2025-07-08 19:13:40 -04:00
const handleRemove = async (event) => {
event.preventDefault();
await deleteMonitor({ monitor: { id: monitorId }, redirect: "/pagespeed" });
2025-07-08 19:13:40 -04:00
};
const isBusy = isLoading || isCreating || isDeleting || isUpdating || isPausing;
if (Object.keys(monitor).length === 0) {
return <SkeletonLayout />;
}
2025-07-08 19:13:40 -04:00
return (
<Box
sx={{
"& h1": { color: theme.palette.primary.contrastText },
}}
>
<Breadcrumbs list={CRUMBS} />
<Stack
component="form"
onSubmit={onSubmit}
noValidate
spellCheck="false"
gap={theme.spacing(12)}
mt={theme.spacing(6)}
>
<Stack
direction="row"
gap={theme.spacing(2)}
>
<Box>
<Typography
component="h1"
variant="h1"
2025-07-08 19:13:40 -04:00
>
<Typography
component="span"
fontSize="inherit"
color={
!isCreate ? theme.palette.primary.contrastTextSecondary : undefined
}
>
{!isCreate ? monitor.name : t("createYour") + " "}
</Typography>
{isCreate ? (
2025-07-08 19:13:40 -04:00
<Typography
component="span"
fontSize="inherit"
fontWeight="inherit"
color={theme.palette.primary.contrastTextSecondary}
2025-07-08 19:13:40 -04:00
>
{t("pageSpeedMonitor")}
2025-07-08 19:13:40 -04:00
</Typography>
) : (
<></>
)}
</Typography>
{!isCreate && (
<Stack
direction="row"
alignItems="center"
height="fit-content"
gap={theme.spacing(2)}
>
<Tooltip
title={pagespeedStatusMsg[determineState(monitor)]}
disableInteractive
slotProps={{
popper: {
modifiers: [
{
name: "offset",
options: { offset: [0, -8] },
2025-07-08 19:13:40 -04:00
},
],
},
}}
2025-07-08 19:13:40 -04:00
>
<Box>
<PulseDot color={statusColor[determineState(monitor)]} />
</Box>
</Tooltip>
2025-07-08 19:13:40 -04:00
<Typography
component="h2"
variant="monitorUrl"
2025-07-08 19:13:40 -04:00
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."}
2025-07-08 19:13:40 -04:00
</Typography>
<Typography
position="relative"
variant="body2"
ml={theme.spacing(6)}
mt={theme.spacing(1)}
sx={{
"&:before": {
position: "absolute",
content: `""`,
width: theme.spacing(2),
height: theme.spacing(2),
borderRadius: "50%",
backgroundColor: theme.palette.primary.contrastTextTertiary,
opacity: 0.8,
left: theme.spacing(-5),
top: "50%",
transform: "translateY(-50%)",
},
}}
>
{t("editing")}
2025-07-08 19:13:40 -04:00
</Typography>
</Stack>
)}
</Box>
{!isCreate && (
<Box
alignSelf="flex-end"
ml="auto"
>
<Button
onClick={handlePause}
loading={isBusy}
variant="contained"
color="secondary"
sx={{
pl: theme.spacing(4),
pr: theme.spacing(6),
"& svg": {
mr: theme.spacing(2),
"& path": {
stroke: theme.palette.primary.contrastTextTertiary,
strokeWidth: 0.1,
},
},
}}
2025-07-08 19:13:40 -04:00
>
{monitor?.isActive ? (
<>
2026-01-15 23:39:26 -05:00
<Icon
name="PauseCircle"
size={20}
/>
{t("pause")}
</>
) : (
<>
2026-01-15 23:39:26 -05:00
<Icon
name="PlayCircle"
size={20}
/>
{t("resume")}
</>
)}
</Button>
<Button
loading={isBusy}
variant="contained"
color="error"
onClick={() => setIsOpen(true)}
sx={{ ml: theme.spacing(6) }}
>
{t("remove")}
</Button>
</Box>
)}
</Stack>
<ConfigBox>
<Box>
<Typography
component="h2"
variant="h2"
>
{t("settingsGeneralSettings")}
</Typography>
<Typography component="p">
{t("pageSpeedConfigureSettingsDescription")}
</Typography>
</Box>
<Stack
gap={!isCreate ? theme.spacing(20) : theme.spacing(15)}
sx={{
".MuiInputBase-root:has(> .Mui-disabled)": {
backgroundColor: theme.palette.tertiary.main,
},
}}
>
<TextInput
type={"url"}
name="url"
id="monitor-url"
label={!isCreate ? t("url") : t("urlMonitor")}
startAdornment={isCreate ? <HttpAdornment https={https} /> : undefined}
placeholder="random.website.com"
value={monitor.url || ""}
onChange={handleChange}
onBlur={isCreate ? handleBlur : undefined}
error={!!errors["url"]}
helperText={errors["url"]}
disabled={!isCreate}
/>
<TextInput
type="text"
id="monitor-name"
name="name"
label={t("monitorDisplayName")}
isOptional={true}
placeholder="Google"
value={monitor.name || ""}
onChange={handleChange}
error={!!errors["name"]}
helperText={errors["name"]}
/>
</Stack>
</ConfigBox>
{isCreate && (
<ConfigBox>
<Box>
<Typography
component="h2"
variant="h2"
>
{t("distributedUptimeCreateChecks")}
</Typography>
<Typography component="p">
{t("distributedUptimeCreateChecksDescription")}
</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
<Stack gap={theme.spacing(6)}>
<Radio
id="monitor-checks-http"
title="PageSpeed"
desc={t("pageSpeedLighthouseAPI")}
size="small"
value="http"
checked={monitor.type === "pagespeed"}
2025-07-08 19:13:40 -04:00
/>
<ButtonGroup sx={{ ml: "32px" }}>
<Button
variant="group"
filled={https.toString()}
onClick={() => setHttps(true)}
>
{t("https")}
</Button>
<Button
variant="group" // Why does this work?
filled={(!https).toString()} // There's nothing in the docs about this either
onClick={() => setHttps(false)}
>
{t("http")}
</Button>
</ButtonGroup>
2025-07-08 19:13:40 -04:00
</Stack>
{errors["type"] ? (
2025-07-08 19:13:40 -04:00
<Box>
<Typography
component="p"
color={theme.palette.error.contrastText}
2025-07-08 19:13:40 -04:00
>
{errors["type"]}
2025-07-08 19:13:40 -04:00
</Typography>
</Box>
) : (
""
)}
2025-07-08 19:13:40 -04:00
</Stack>
</ConfigBox>
)}
<ConfigBox>
<Box>
<Typography
component="h2"
variant="h2"
>
{t("notificationConfig.title")}
</Typography>
<Typography component="p">{t("notificationConfig.description")}</Typography>
</Box>
<NotificationsConfig
notifications={notifications}
setMonitor={setMonitor}
setNotifications={isCreate ? undefined : monitor.notifications}
/>
</ConfigBox>
<ConfigBox>
<Box>
<Typography
component="h2"
variant="h2"
>
{t("distributedUptimeCreateAdvancedSettings")}
</Typography>
</Box>
<Stack gap={theme.spacing(isCreate ? 12 : 20)}>
<Select
id="monitor-interval"
name="interval"
label={t("checkFrequency")}
value={monitor?.interval / MS_PER_MINUTE || 3}
onChange={handleChange}
items={FREQUENCIES}
/>
2025-07-08 19:13:40 -04:00
</Stack>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
mt={isCreate ? undefined : "auto"}
>
<Button
type="submit"
variant="contained"
color="accent"
loading={isBusy}
disabled={!Object.values(errors).every((value) => value === undefined)}
sx={isCreate ? undefined : { px: theme.spacing(12) }}
>
{isCreate ? t("createMonitor") : t("settingsSave")}
</Button>
</Stack>
</Stack>
{!isCreate && (
2025-07-08 19:13:40 -04:00
<Dialog
open={isOpen}
theme={theme}
title={t("deleteDialogTitle")}
description={t("deleteDialogDescription")}
onCancel={() => setIsOpen(false)}
confirmationButtonLabel={t("delete")}
onConfirm={handleRemove}
/>
)}
</Box>
);
};
export default PageSpeedSetup;