[Uptime]: Merged Configure into Create Component

This commit is contained in:
Jesulayomy committed 2025-07-23 19:20:37 -04:00
1 parent 56d8224fb9
commit a004b7b450
4 files changed
+341 -743

No files matched your search

@@ -1,11 +0,0 @@
.configure-monitor button.MuiButtonBase-root {
height: var(--env-var-height-2);
}
.configure-monitor .MuiStack-root:has(span.MuiTypography-root.input-error) {
position: relative;
}
.configure-monitor span.MuiTypography-root.input-error {
position: absolute;
top: 100%;
}
-526
View File
@@ -1,526 +0,0 @@
// Components
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import Button from "@mui/material/Button";
import FormControlLabel from "@mui/material/FormControlLabel";
import Switch from "@mui/material/Switch";
import ConfigBox from "../../../Components/ConfigBox";
import Breadcrumbs from "../../../Components/Breadcrumbs";
import TextInput from "../../../Components/Inputs/TextInput";
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import Select from "../../../Components/Inputs/Select";
import Dialog from "../../../Components/Dialog";
import PulseDot from "../../../Components/Animated/PulseDot";
import Checkbox from "../../../Components/Inputs/Checkbox";
// Utils
import { useParams } from "react-router";
import { useTheme } from "@emotion/react";
import { useState } from "react";
import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils";
import { useTranslation } from "react-i18next";
import PauseOutlinedIcon from "@mui/icons-material/PauseOutlined";
import PlayArrowOutlinedIcon from "@mui/icons-material/PlayArrowOutlined";
import { useMonitorUtils } from "../../../Hooks/useMonitorUtils";
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
import {
useDeleteMonitor,
useUpdateMonitor,
usePauseMonitor,
useFetchMonitorById,
} from "../../../Hooks/monitorHooks";
import NotificationsConfig from "../../../Components/NotificationConfig";
/**
* Parses a URL string and returns a URL object.
*
* @param {string} url - The URL string to parse.
* @returns {URL} - The parsed URL object if valid, otherwise an empty string.
*/
const parseUrl = (url) => {
try {
return new URL(url);
} catch (error) {
return null;
}
};
/**
* Configure page displays monitor configurations and allows for editing actions.
* @component
*/
const Configure = () => {
const { monitorId } = useParams();
// Local state
const [form, setForm] = useState({
ignoreTlsErrors: false,
interval: 60000,
matchMethod: "equal",
expectedValue: "",
jsonPath: "",
notifications: [],
port: "",
type: "http",
});
const [useAdvancedMatching, setUseAdvancedMatching] = useState(false);
const [updateTrigger, setUpdateTrigger] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const [errors, setErrors] = useState({});
const triggerUpdate = () => {
setUpdateTrigger(!updateTrigger);
};
// Network
const [notifications, notificationsAreLoading, notificationsError] =
useGetNotificationsByTeamId();
const [pauseMonitor, isPausing, pauseError] = usePauseMonitor({});
const [deleteMonitor, isDeleting] = useDeleteMonitor();
const [updateMonitor, isUpdating] = useUpdateMonitor();
const [isLoading] = useFetchMonitorById({
monitorId,
setMonitor: setForm,
updateTrigger,
});
const MS_PER_MINUTE = 60000;
const theme = useTheme();
const matchMethodOptions = [
{ _id: "equal", name: "Equal" },
{ _id: "include", name: "Include" },
{ _id: "regex", name: "Regex" },
];
const frequencies = [
{ _id: 1, name: "1 minute" },
{ _id: 2, name: "2 minutes" },
{ _id: 3, name: "3 minutes" },
{ _id: 4, name: "4 minutes" },
{ _id: 5, name: "5 minutes" },
];
const expectedValuePlaceholders = {
regex: "^(success|ok)$",
equal: "success",
include: "ok",
};
// Handlers
const handlePause = async () => {
const res = await pauseMonitor({ monitorId: form?._id, triggerUpdate });
if (typeof res !== "undefined") {
triggerUpdate();
}
};
const handleRemove = async (event) => {
event.preventDefault();
await deleteMonitor({ monitor: form, redirect: "/uptime" });
};
const onChange = (event) => {
let { name, value, checked } = event.target;
if (name === "ignoreTlsErrors") {
value = checked;
}
if (name === "useAdvancedMatching") {
setForm((prevForm) => {
return {
...prevForm,
matchMethod: "equal",
};
});
setUseAdvancedMatching(!useAdvancedMatching);
return;
}
if (name === "interval") {
value = value * MS_PER_MINUTE;
}
setForm({ ...form, [name]: value });
const validation = monitorValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
const updatedErrors = { ...prev };
if (validation.error) updatedErrors[name] = validation.error.details[0].message;
else delete updatedErrors[name];
return updatedErrors;
});
};
const onSubmit = async (e) => {
e.preventDefault();
const toSubmit = {
_id: form._id,
url: form.url,
name: form.name,
type: form.type,
matchMethod: form.matchMethod,
expectedValue: form.expectedValue,
jsonPath: form.jsonPath,
interval: form.interval,
teamId: form.teamId,
userId: form.userId,
port: form.port,
ignoreTlsErrors: form.ignoreTlsErrors,
};
if (!useAdvancedMatching) {
toSubmit.matchMethod = "";
toSubmit.expectedValue = "";
toSubmit.jsonPath = "";
}
const validation = monitorValidation.validate(toSubmit, {
abortEarly: false,
});
if (validation.error) {
const newErrors = {};
validation.error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors(newErrors);
createToast({ body: "Please check the form for errors." });
return;
}
toSubmit.notifications = form.notifications;
await updateMonitor({ monitor: toSubmit, redirect: "/uptime" });
};
// Parse the URL
const parsedUrl = parseUrl(form?.url);
const protocol = parsedUrl?.protocol?.replace(":", "") || "";
const { determineState, statusColor } = useMonitorUtils();
const { t } = useTranslation();
return (
<Stack gap={theme.spacing(10)}>
<Breadcrumbs
list={[
{ name: "uptime", path: "/uptime" },
{ name: "details", path: `/uptime/${monitorId}` },
{ name: "configure", path: `/uptime/configure/${monitorId}` },
]}
/>
<Stack
component="form"
onSubmit={onSubmit}
noValidate
spellCheck="false"
gap={theme.spacing(12)}
flex={1}
>
<Stack
direction="row"
gap={theme.spacing(12)}
>
<Box>
<Typography
component="h1"
variant="monitorName"
>
{form.name}
</Typography>
<Stack
direction="row"
alignItems="center"
height="fit-content"
gap={theme.spacing(2)}
>
<Tooltip
title={t(`statusMsg.${[determineState(form)]}`)}
disableInteractive
slotProps={{
popper: {
modifiers: [
{
name: "offset",
options: {
offset: [0, -8],
},
},
],
},
}}
>
<Box>
<PulseDot color={statusColor[determineState(form)]} />
</Box>
</Tooltip>
<Typography
component="h2"
variant="monitorUrl"
>
{form.url?.replace(/^https?:\/\//, "") || "..."}
</Typography>
<Typography
position="relative"
variant="body2"
ml={theme.spacing(6)}
mt={theme.spacing(1)}
sx={{
"&:before": {
position: "absolute",
content: `""`,
width: 4,
height: 4,
borderRadius: "50%",
backgroundColor: theme.palette.primary.contrastTextTertiary,
opacity: 0.8,
left: -10,
top: "50%",
transform: "translateY(-50%)",
},
}}
>
{t("editing")}
</Typography>
</Stack>
</Box>
<Box
justifyContent="space-between"
sx={{
alignSelf: "flex-end",
ml: "auto",
display: "flex",
gap: theme.spacing(2),
}}
>
<Button
variant="contained"
color="secondary"
loading={isPausing}
startIcon={
form?.isActive ? <PauseOutlinedIcon /> : <PlayArrowOutlinedIcon />
}
onClick={handlePause}
>
{form?.isActive ? t("pause") : t("resume")}
</Button>
<Button
loading={isLoading}
variant="contained"
color="error"
sx={{ px: theme.spacing(8) }}
onClick={() => setIsOpen(true)}
>
{t("remove")}
</Button>
</Box>
</Stack>
<ConfigBox>
<Box>
<Typography
component="h2"
variant="h2"
>
{t("settingsGeneralSettings")}
</Typography>
<Typography component="p">{t("distributedUptimeCreateSelectURL")}</Typography>
</Box>
<Stack gap={theme.spacing(20)}>
<TextInput
type={form?.type === "http" ? "url" : "text"}
https={protocol === "https"}
startAdornment={
form?.type === "http" && <HttpAdornment https={protocol === "https"} />
}
id="monitor-url"
label={t("urlMonitor")}
placeholder="google.com"
value={parsedUrl?.host || form?.url || ""}
disabled={true}
/>
<TextInput
name="port"
type="number"
label={t("portToMonitor")}
placeholder="5173"
value={form.port || ""}
onChange={onChange}
error={errors["port"] ? true : false}
helperText={errors["port"]}
hidden={form.type !== "port"}
/>
<TextInput
name="name"
type="text"
label={t("displayName")}
isOptional={true}
placeholder="Google"
value={form?.name || ""}
onChange={onChange}
error={errors["name"] ? true : false}
helperText={errors["name"]}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">{t("notificationConfig.title")}</Typography>
<Typography component="p">{t("notificationConfig.description")}</Typography>
</Box>
<NotificationsConfig
notifications={notifications}
setMonitor={setForm}
setNotifications={form.notifications}
/>
</ConfigBox>
<ConfigBox>
<Box>
<Typography
component="h2"
variant="h2"
>
{t("ignoreTLSError")}
</Typography>
<Typography component="p">{t("ignoreTLSErrorDescription")}</Typography>
</Box>
<Stack>
<FormControlLabel
sx={{ marginLeft: 0 }}
control={
<Switch
name="ignoreTlsErrors"
checked={form.ignoreTlsErrors ?? false}
onChange={onChange}
sx={{ mr: theme.spacing(2) }}
/>
}
label={t("tlsErrorIgnored")}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography
component="h2"
variant="h2"
>
{t("distributedUptimeCreateAdvancedSettings")}
</Typography>
</Box>
<Stack gap={theme.spacing(20)}>
<Select
name="interval"
label={t("checkFrequency")}
value={form?.interval / MS_PER_MINUTE || 1}
onChange={onChange}
items={frequencies}
/>
<Checkbox
name="useAdvancedMatching"
label={t("advancedMatching")}
isChecked={useAdvancedMatching}
onChange={onChange}
/>
{form.type === "http" && useAdvancedMatching && (
<>
<Select
name="matchMethod"
label={t("matchMethod")}
value={form.matchMethod || "equal"}
onChange={onChange}
items={matchMethodOptions}
/>
<Stack>
<TextInput
type="text"
name="expectedValue"
label={t("expectedValue")}
isOptional={true}
placeholder={expectedValuePlaceholders[form.matchMethod || "equal"]}
value={form.expectedValue}
onChange={onChange}
error={errors["expectedValue"] ? true : false}
helperText={errors["expectedValue"]}
/>
<Typography
component="span"
color={theme.palette.primary.contrastTextTertiary}
opacity={0.8}
>
{t("uptimeCreate")}
</Typography>
</Stack>
<Stack>
<TextInput
name="jsonPath"
type="text"
label="JSON Path"
isOptional={true}
placeholder="data.status"
value={form.jsonPath}
onChange={onChange}
error={errors["jsonPath"] ? true : false}
helperText={errors["jsonPath"]}
/>
<Typography
component="span"
color={theme.palette.primary.contrastTextTertiary}
opacity={0.8}
>
{t("uptimeCreateJsonPath")}&nbsp;
<Typography
component="a"
href="https://jmespath.org/"
target="_blank"
color="info"
>
jmespath.org
</Typography>
&nbsp;{t("uptimeCreateJsonPathQuery")}
</Typography>
</Stack>
</>
)}
</Stack>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
mt="auto"
>
<Button
disabled={isDeleting || isUpdating}
type="submit"
variant="contained"
color="accent"
loading={isLoading}
sx={{ px: theme.spacing(12) }}
>
{t("settingsSave")}
</Button>
</Stack>
</Stack>
<Dialog
open={isOpen}
theme={theme}
title="Do you really want to delete this monitor?"
description="Once deleted, this monitor cannot be retrieved."
onCancel={() => setIsOpen(false)}
confirmationButtonLabel="Delete"
onConfirm={handleRemove}
isLoading={isLoading}
/>
</Stack>
);
};
export default Configure;
@@ -1,90 +0,0 @@
import { Box, Skeleton, Stack } from "@mui/material";
import { useTheme } from "@emotion/react";
/**
* Renders a skeleton layout.
*
* @returns {JSX.Element}
*/
const SkeletonLayout = () => {
const theme = useTheme();
return (
<>
<Skeleton
variant="rounded"
width="15%"
height={34}
/>
<Stack
gap={theme.spacing(20)}
mt={theme.spacing(6)}
>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(4)}
>
<Skeleton
variant="circular"
style={{ minWidth: 24, minHeight: 24 }}
/>
<Box width="80%">
<Skeleton
variant="rounded"
width="50%"
height={24}
sx={{ mb: theme.spacing(4) }}
/>
<Skeleton
variant="rounded"
width="50%"
height={18}
/>
</Box>
<Stack
direction="row"
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;
+341 -116
View File
@@ -1,4 +1,14 @@
//Components //Components
import {
Box,
Button,
ButtonGroup,
FormControlLabel,
Stack,
Switch,
Tooltip,
Typography,
} from "@mui/material";
import Breadcrumbs from "../../../Components/Breadcrumbs"; 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";
@@ -6,132 +16,189 @@ import Radio from "../../../Components/Inputs/Radio";
import Select from "../../../Components/Inputs/Select"; import Select from "../../../Components/Inputs/Select";
import ConfigBox from "../../../Components/ConfigBox"; import ConfigBox from "../../../Components/ConfigBox";
import NotificationsConfig from "../../../Components/NotificationConfig"; import NotificationsConfig from "../../../Components/NotificationConfig";
import Button from "@mui/material/Button";
import ButtonGroup from "@mui/material/ButtonGroup";
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import Switch from "@mui/material/Switch";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "../../../Components/Inputs/Checkbox"; import Checkbox from "../../../Components/Inputs/Checkbox";
import Dialog from "../../../Components/Dialog";
import PulseDot from "../../../Components/Animated/PulseDot";
import SkeletonLayout from "./skeleton";
// Utils // Utils
import { useParams } from "react-router";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { useTranslation } from "react-i18next";
import {
PauseOutlined as PauseOutlinedIcon,
PlayArrowOutlined as PlayArrowOutlinedIcon,
} from "@mui/icons-material";
import { useMonitorUtils } from "../../../Hooks/useMonitorUtils";
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications"; import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
import { useCreateMonitor, useFetchMonitorById } from "../../../Hooks/monitorHooks"; import { useCreateMonitor, useFetchMonitorById } from "../../../Hooks/monitorHooks";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import {
useDeleteMonitor,
useUpdateMonitor,
usePauseMonitor,
useFetchMonitorById,
} from "../../../Hooks/monitorHooks";
import { useCreateMonitor } from "../../../Hooks/monitorHooks";
const CreateMonitor = () => { /**
// Local state * Parses a URL string and returns a URL object.
const [errors, setErrors] = useState({}); *
const [https, setHttps] = useState(true); * @param {string} url - The URL string to parse.
const [useAdvancedMatching, setUseAdvancedMatching] = useState(false); * @returns {URL} - The parsed URL object if valid, otherwise an empty string.
*/
const parseUrl = (url) => {
try {
return new URL(url);
} catch (error) {
return null;
}
};
/**
* Create page renders monitor creation or configuration views.
* @component
*/
const UptimeCreate = () => {
const { monitorId } = useParams();
const isCreate = typeof monitorId === "undefined";
// States
const [monitor, setMonitor] = useState({ const [monitor, setMonitor] = useState({
url: "",
name: "",
type: "http", type: "http",
matchMethod: "equal", matchMethod: "equal",
expectedValue: "", expectedValue: "",
jsonPath: "", jsonPath: "",
notifications: [], notifications: [],
interval: 1, interval: 60000,
ignoreTlsErrors: false, ignoreTlsErrors: false,
...(isCreate ? { url: "", name: "" } : { port: undefined }),
}); });
const [errors, setErrors] = useState({});
// Setup const [https, setHttps] = useState(true);
const MS_PER_MINUTE = 60000; const [isOpen, setIsOpen] = useState(false);
const theme = useTheme(); const [useAdvancedMatching, setUseAdvancedMatching] = useState(false);
const { t } = useTranslation(); const [updateTrigger, setUpdateTrigger] = useState(false);
const [notifications, notificationsAreLoading, error] = useGetNotificationsByTeamId(); const triggerUpdate = () => {
const [createMonitor, isCreating] = useCreateMonitor(); setUpdateTrigger(!updateTrigger);
const { monitorId } = useParams();
const formatAndSet = (monitor) => {
monitor.interval = monitor.interval / MS_PER_MINUTE;
setMonitor(monitor);
}; };
// Hooks
const [notifications, notificationsAreLoading, notificationsError] =
useGetNotificationsByTeamId();
const { determineState, statusColor } = useMonitorUtils();
// Network
const [isLoading] = useFetchMonitorById({ const [isLoading] = useFetchMonitorById({
monitorId, monitorId,
setMonitor: formatAndSet, setMonitor: formatAndSet,
updateTrigger: true, updateTrigger: true,
}); });
const [createMonitor, isCreating] = useCreateMonitor();
const [pauseMonitor, isPausing] = usePauseMonitor({});
const [deleteMonitor, isDeleting] = useDeleteMonitor();
const [updateMonitor, isUpdating] = useUpdateMonitor();
const SELECT_VALUES = [ // Setup
{ _id: 1, name: "1 minute" }, const theme = useTheme();
{ _id: 2, name: "2 minutes" }, const { t } = useTranslation();
{ _id: 3, name: "3 minutes" }, const formatAndSet = (monitor) => {
{ _id: 4, name: "4 minutes" }, monitor.interval = monitor.interval / MS_PER_MINUTE;
{ _id: 5, name: "5 minutes" }, setMonitor(monitor);
];
const matchMethodOptions = [
{ _id: "equal", name: "Equal" },
{ _id: "include", name: "Include" },
{ _id: "regex", name: "Regex" },
];
const expectedValuePlaceholders = {
regex: "^(success|ok)$",
equal: "success",
include: "ok",
}; };
// Constants
const MS_PER_MINUTE = 60000;
const FREQUENCIES = [
{ _id: 1, name: t("time.oneMinute") },
{ _id: 2, name: t("time.twoMinutes") },
{ _id: 3, name: t("time.threeMinutes") },
{ _id: 4, name: t("time.fourMinutes") },
{ _id: 5, name: t("time.fiveMinutes") },
];
const CRUMBS = [
{ name: "uptime", path: "/uptime" },
...(isCreate
? [{ name: "create", path: `/uptime/create` }]
: [
{ name: "details", path: `/uptime/${monitorId}` },
{ name: "configure", path: `/uptime/configure/${monitorId}` },
]),
];
const matchMethodOptions = [
{ _id: "equal", name: t("matchMethodOptions.equal") },
{ _id: "include", name: t("matchMethodOptions.include") },
{ _id: "regex", name: t("matchMethodOptions.regex") },
];
const expectedValuePlaceholders = {
regex: t("matchMethodOptions.regexPlaceholder"),
equal: t("matchMethodOptions.equalPlaceholder"),
include: t("matchMethodOptions.includePlaceholder"),
};
const monitorTypeMaps = { const monitorTypeMaps = {
http: { http: {
label: "URL to monitor", label: t("monitorType.http.label"),
placeholder: "google.com", placeholder: t("monitorType.http.placeholder"),
namePlaceholder: "Google", namePlaceholder: t("monitorType.http.namePlaceholder"),
}, },
ping: { ping: {
label: "IP address to monitor", label: t("monitorType.ping.label"),
placeholder: "1.1.1.1", placeholder: t("monitorType.ping.placeholder"),
namePlaceholder: "Google", namePlaceholder: t("monitorType.ping.namePlaceholder"),
}, },
docker: { docker: {
label: "Container ID", label: t("monitorType.docker.label"),
placeholder: "abc123", placeholder: t("monitorType.docker.placeholder"),
namePlaceholder: "My Container", namePlaceholder: t("monitorType.docker.namePlaceholder"),
}, },
port: { port: {
label: "URL to monitor", label: t("monitorType.port.label"),
placeholder: "localhost", placeholder: t("monitorType.port.placeholder"),
namePlaceholder: "Localhost:5173", namePlaceholder: t("monitorType.port.namePlaceholder"),
}, },
}; };
const BREADCRUMBS = [
{ name: "uptime", path: "/uptime" },
{ name: "create", path: `/uptime/create` },
];
// Handlers // Handlers
const onSubmit = async (event) => { const onSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const { notifications, ...rest } = monitor; const { notifications, ...rest } = monitor;
let form = { let form = {};
if (isCreate) {
form = {
...rest, ...rest,
url: url:
//prepending protocol for url
monitor.type === "http" monitor.type === "http"
? `http${https ? "s" : ""}://` + monitor.url ? `http${https ? "s" : ""}://` + monitor.url
: monitor.url, : monitor.url,
port: monitor.type === "port" ? monitor.port : undefined, port: monitor.type === "port" ? monitor.port : undefined,
name: monitor.name || monitor.url.substring(0, 50), name: monitor.name || monitor.url.substring(0, 50),
type: monitor.type, type: monitor.type,
interval: monitor.interval * MS_PER_MINUTE, interval: monitor.interval,
}; };
} else {
// If not using advanced matching, remove advanced settings form = {
_id: monitor._id,
url: monitor.url,
name: monitor.name || monitor.url.substring(0, 50),
type: monitor.type,
matchMethod: monitor.matchMethod,
expectedValue: monitor.expectedValue,
jsonPath: monitor.jsonPath,
interval: monitor.interval,
teamId: monitor.teamId,
userId: monitor.userId,
port: monitor.type === "port" ? monitor.port : undefined,
ignoreTlsErrors: monitor.ignoreTlsErrors,
};
}
if (!useAdvancedMatching) { if (!useAdvancedMatching) {
form.matchMethod = undefined; form.matchMethod = isCreate ? undefined : "";
form.expectedValue = undefined; form.expectedValue = isCreate ? undefined : "";
form.jsonPath = undefined; form.jsonPath = isCreate ? undefined : "";
} }
const { error } = monitorValidation.validate(form, { const { error } = monitorValidation.validate(form, {
@@ -144,7 +211,7 @@ const CreateMonitor = () => {
newErrors[err.path[0]] = err.message; newErrors[err.path[0]] = err.message;
}); });
setErrors(newErrors); setErrors(newErrors);
createToast({ body: "Please check the form for errors." }); createToast({ body: t("checkFormError") });
return; return;
} }
@@ -154,15 +221,18 @@ const CreateMonitor = () => {
notifications: monitor.notifications, notifications: monitor.notifications,
}; };
if (isCreate) {
await createMonitor({ monitor: form, redirect: "/uptime" }); await createMonitor({ monitor: form, redirect: "/uptime" });
} else {
await updateMonitor({ monitor: form, redirect: "/uptime" });
}
}; };
const onChange = (event) => { const onChange = (event) => {
const { name, value, checked } = event.target; let { name, value, checked } = event.target;
let newValue = value;
if (name === "ignoreTlsErrors") { if (name === "ignoreTlsErrors") {
newValue = checked; value = checked;
} }
if (name === "useAdvancedMatching") { if (name === "useAdvancedMatching") {
@@ -170,15 +240,14 @@ const CreateMonitor = () => {
return; return;
} }
const updatedMonitor = { if (name === "interval") {
...monitor, value = value * MS_PER_MINUTE;
[name]: newValue, }
};
setMonitor(updatedMonitor); setMonitor((prev) => ({ ...prev, [name]: value }));
const { error } = monitorValidation.validate( const { error } = monitorValidation.validate(
{ type: monitor.type, [name]: newValue }, { type: monitor.type, [name]: value },
{ abortEarly: false } { abortEarly: false }
); );
@@ -188,10 +257,49 @@ const CreateMonitor = () => {
})); }));
}; };
const handlePause = async () => {
await pauseMonitor({ monitorId, triggerUpdate });
};
const handleRemove = async (event) => {
event.preventDefault();
await deleteMonitor({ monitor, redirect: "/uptime" });
};
const isBusy = isLoading || isCreating || isDeleting || isUpdating || isPausing;
const parsedUrl = parseUrl(monitor?.url);
const protocol = parsedUrl?.protocol?.replace(":", "") || "";
if (Object.keys(monitor).length === 0) {
return <SkeletonLayout />;
}
useEffect(() => {
if (!isCreate) {
if (monitor.matchMethod) {
setUseAdvancedMatching(true);
} else {
setUseAdvancedMatching(false);
}
}
}, [monitor]);
return ( return (
<Stack gap={theme.spacing(10)}> <Stack gap={theme.spacing(10)}>
<Breadcrumbs list={BREADCRUMBS} /> <Breadcrumbs list={CRUMBS} />
<Stack
component="form"
onSubmit={onSubmit}
noValidate
spellCheck="false"
gap={theme.spacing(12)}
flex={1}
>
<Stack
direction="row"
gap={theme.spacing(12)}
>
<Box>
<Typography <Typography
component="h1" component="h1"
variant="h1" variant="h1"
@@ -199,25 +307,115 @@ const CreateMonitor = () => {
<Typography <Typography
component="span" component="span"
fontSize="inherit" fontSize="inherit"
color={
!isCreate ? theme.palette.primary.contrastTextSecondary : undefined
}
> >
{t("createYour")}{" "} {!isCreate ? monitor.name : t("createYour") + " "}
</Typography> </Typography>
{isCreate && (
<Typography <Typography
component="span" component="span"
variant="h2"
fontSize="inherit" fontSize="inherit"
fontWeight="inherit" fontWeight="inherit"
color={theme.palette.primary.contrastTextSecondary}
> >
{t("monitor")} {t("monitor")}
</Typography> </Typography>
)}
</Typography> </Typography>
{!isCreate && (
<Stack <Stack
component="form" direction="row"
noValidate alignItems="center"
gap={theme.spacing(12)} height="fit-content"
mt={theme.spacing(6)} gap={theme.spacing(2)}
onSubmit={onSubmit}
> >
<Tooltip
title={t(`statusMsg.${[determineState(monitor)]}`)}
disableInteractive
slotProps={{
popper: {
modifiers: [
{
name: "offset",
options: {
offset: [0, -8],
},
},
],
},
}}
>
<Box>
<PulseDot color={statusColor[determineState(monitor)]} />
</Box>
</Tooltip>
<Typography
component="h2"
variant="monitorUrl"
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography>
<Typography
position="relative"
variant="body2"
ml={theme.spacing(6)}
mt={theme.spacing(1)}
sx={{
"&:before": {
position: "absolute",
content: `""`,
width: 4,
height: 4,
borderRadius: "50%",
backgroundColor: theme.palette.primary.contrastTextTertiary,
opacity: 0.8,
left: -10,
top: "50%",
transform: "translateY(-50%)",
},
}}
>
{t("editing")}
</Typography>
</Stack>
)}
</Box>
{!isCreate && (
<Box
justifyContent="space-between"
sx={{
alignSelf: "flex-end",
ml: "auto",
display: "flex",
gap: theme.spacing(2),
}}
>
<Button
variant="contained"
color="secondary"
loading={isBusy}
startIcon={
monitor?.isActive ? <PauseOutlinedIcon /> : <PlayArrowOutlinedIcon />
}
onClick={handlePause}
>
{monitor?.isActive ? t("pause") : t("resume")}
</Button>
<Button
loading={isBusy}
variant="contained"
color="error"
sx={{ px: theme.spacing(8) }}
onClick={() => setIsOpen(true)}
>
{t("remove")}
</Button>
</Box>
)}
</Stack>
{isCreate && (
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography <Typography
@@ -304,6 +502,7 @@ const CreateMonitor = () => {
)} )}
</Stack> </Stack>
</ConfigBox> </ConfigBox>
)}
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography <Typography
@@ -313,30 +512,39 @@ const CreateMonitor = () => {
{t("settingsGeneralSettings")} {t("settingsGeneralSettings")}
</Typography> </Typography>
<Typography component="p"> <Typography component="p">
{t(`uptimeGeneralInstructions.${monitor.type}`)} {isCreate
? t(`uptimeGeneralInstructions.${monitor.type}`)
: t("distributedUptimeCreateSelectURL")}
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(15)}> <Stack gap={theme.spacing(20)}>
<TextInput <TextInput
id="monitor-url"
name="url" name="url"
type={monitor.type === "http" ? "url" : "text"} type={monitor?.type === "http" ? "url" : "text"}
startAdornment={ label={
monitor.type === "http" ? <HttpAdornment https={https} /> : null (monitor.type === "http" || monitor.type === "port") && !isCreate
? t("url")
: monitorTypeMaps[monitor.type].label || t("urlMonitor")
} }
label={monitorTypeMaps[monitor.type].label || "URL to monitor"}
https={https}
placeholder={monitorTypeMaps[monitor.type].placeholder || ""} placeholder={monitorTypeMaps[monitor.type].placeholder || ""}
value={monitor.url} value={parsedUrl?.host || monitor?.url || ""}
onChange={onChange} https={isCreate ? https : protocol === "https"}
error={errors["url"] ? true : false} startAdornment={
monitor?.type === "http" && (
<HttpAdornment https={isCreate ? https : protocol === "https"} />
)
}
helperText={errors["url"]} helperText={errors["url"]}
onChange={onChange}
disabled={!isCreate}
/> />
<TextInput <TextInput
name="port" name="port"
type="number" type="number"
label={t("portToMonitor")} label={t("portToMonitor")}
placeholder="5173" placeholder="5173"
value={monitor.port} value={monitor.port || ""}
onChange={onChange} onChange={onChange}
error={errors["port"] ? true : false} error={errors["port"] ? true : false}
helperText={errors["port"]} helperText={errors["port"]}
@@ -347,8 +555,8 @@ const CreateMonitor = () => {
type="text" type="text"
label={t("displayName")} label={t("displayName")}
isOptional={true} isOptional={true}
placeholder={monitorTypeMaps[monitor.type].namePlaceholder || ""} placeholder={monitorTypeMaps[monitor.type].namePlaceholder}
value={monitor.name} value={monitor.name || ""}
onChange={onChange} onChange={onChange}
error={errors["name"] ? true : false} error={errors["name"] ? true : false}
helperText={errors["name"]} helperText={errors["name"]}
@@ -363,6 +571,7 @@ const CreateMonitor = () => {
<NotificationsConfig <NotificationsConfig
notifications={notifications} notifications={notifications}
setMonitor={setMonitor} setMonitor={setMonitor}
setNotifications={isCreate ? null : monitor.notifications}
/> />
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
@@ -377,7 +586,7 @@ const CreateMonitor = () => {
</Box> </Box>
<Stack> <Stack>
<FormControlLabel <FormControlLabel
sx={{ marginLeft: 0 }} sx={{ marginLeft: theme.spacing(0) }}
control={ control={
<Switch <Switch
name="ignoreTlsErrors" name="ignoreTlsErrors"
@@ -399,34 +608,36 @@ const CreateMonitor = () => {
{t("distributedUptimeCreateAdvancedSettings")} {t("distributedUptimeCreateAdvancedSettings")}
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(12)}> <Stack gap={theme.spacing(20)}>
<Select <Select
name="interval" name="interval"
label="Check frequency" label={t("checkFrequency")}
value={monitor.interval || 1} value={monitor?.interval / MS_PER_MINUTE || 1}
onChange={onChange} onChange={onChange}
items={SELECT_VALUES} items={FREQUENCIES}
/> />
{monitor.type === "http" && (
<Checkbox <Checkbox
name="useAdvancedMatching" name="useAdvancedMatching"
label={t("advancedMatching")} label={t("advancedMatching")}
isChecked={useAdvancedMatching} isChecked={useAdvancedMatching}
onChange={onChange} onChange={onChange}
/> />
)}
{monitor.type === "http" && useAdvancedMatching && ( {monitor.type === "http" && useAdvancedMatching && (
<> <>
<Select <Select
name="matchMethod" name="matchMethod"
label="Match Method" label={t("matchMethod")}
value={monitor.matchMethod || "equal"} value={monitor.matchMethod || "equal"}
onChange={onChange} onChange={onChange}
items={matchMethodOptions} items={matchMethodOptions}
/> />
<Stack> <Stack>
<TextInput <TextInput
name="expectedValue"
type="text" type="text"
label="Expected value" name="expectedValue"
label={t("expectedValue")}
isOptional={true} isOptional={true}
placeholder={ placeholder={
expectedValuePlaceholders[monitor.matchMethod || "equal"] expectedValuePlaceholders[monitor.matchMethod || "equal"]
@@ -448,7 +659,7 @@ const CreateMonitor = () => {
<TextInput <TextInput
name="jsonPath" name="jsonPath"
type="text" type="text"
label="JSON Path" label={t("uptimeAdvancedMatching.jsonPath")}
isOptional={true} isOptional={true}
placeholder="data.status" placeholder="data.status"
value={monitor.jsonPath} value={monitor.jsonPath}
@@ -461,7 +672,7 @@ const CreateMonitor = () => {
color={theme.palette.primary.contrastTextTertiary} color={theme.palette.primary.contrastTextTertiary}
opacity={0.8} opacity={0.8}
> >
{t("uptimeCreateJsonPath")}&nbsp; {t("uptimeCreateJsonPath") + " "}
<Typography <Typography
component="a" component="a"
href="https://jmespath.org/" href="https://jmespath.org/"
@@ -470,7 +681,7 @@ const CreateMonitor = () => {
> >
jmespath.org jmespath.org
</Typography> </Typography>
&nbsp;{t("uptimeCreateJsonPathQuery")} {" " + t("uptimeCreateJsonPathQuery")}
</Typography> </Typography>
</Stack> </Stack>
</> </>
@@ -486,14 +697,28 @@ const CreateMonitor = () => {
variant="contained" variant="contained"
color="accent" color="accent"
disabled={!Object.values(errors).every((value) => value === undefined)} disabled={!Object.values(errors).every((value) => value === undefined)}
loading={isCreating} loading={isBusy}
sx={{ px: theme.spacing(12) }}
> >
{t("createMonitor")} {t("settingsSave")}
</Button> </Button>
</Stack> </Stack>
</Stack> </Stack>
{!isCreate && (
<Dialog
open={isOpen}
theme={theme}
title={t("deleteDialogTitle")}
description={t("deleteDialogDescription")}
onCancel={() => setIsOpen(false)}
confirmationButtonLabel={t("delete")}
onConfirm={handleRemove}
isLoading={isLoading}
/>
)}
</Stack> </Stack>
); );
}; };
export default CreateMonitor; export default UptimeCreate;