Merge pull request #2737 from Jesulayomy/fe-infra_monitor_upgrade

[Frontend]: Refactor Infrastructure monitor create Component
This commit is contained in:
Alexander Holliday authored and GitHub committed 2025-08-04 10:05:06 -07:00
commit cd8752c1cb
2 files changed
+244 -91

No files matched your search

+242 -91
View File
@@ -1,78 +1,51 @@
// React, Redux, Router
import { useTheme } from "@emotion/react";
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { useSelector } from "react-redux";
// Utility and Network
import { infrastructureMonitorValidation } from "../../../Validation/validation";
import { useFetchHardwareMonitorById } from "../../../Hooks/monitorHooks";
import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
import { useTranslation } from "react-i18next";
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
import NotificationsConfig from "../../../Components/NotificationConfig";
import {
useUpdateMonitor,
useCreateMonitor,
useFetchGlobalSettings,
} from "../../../Hooks/monitorHooks";
// MUI
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
//Components //Components
import Breadcrumbs from "../../../Components/Breadcrumbs"; import Breadcrumbs from "../../../Components/Breadcrumbs";
import Link from "../../../Components/Link";
import ConfigBox from "../../../Components/ConfigBox"; import ConfigBox from "../../../Components/ConfigBox";
import Dialog from "../../../Components/Dialog";
import FieldWrapper from "../../../Components/Inputs/FieldWrapper";
import Link from "../../../Components/Link";
import PauseCircleOutlineIcon from "@mui/icons-material/PauseCircleOutline";
import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded";
import PulseDot from "../../../Components/Animated/PulseDot";
import Select from "../../../Components/Inputs/Select";
import TextInput from "../../../Components/Inputs/TextInput"; import TextInput from "../../../Components/Inputs/TextInput";
import { Box, Stack, Tooltip, Typography, Button, ButtonGroup } from "@mui/material";
import { CustomThreshold } from "./Components/CustomThreshold";
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments"; import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import Select from "../../../Components/Inputs/Select"; // Utils
import { CustomThreshold } from "./Components/CustomThreshold"; import NotificationsConfig from "../../../Components/NotificationConfig";
import FieldWrapper from "../../../Components/Inputs/FieldWrapper"; import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
import { infrastructureMonitorValidation } from "../../../Validation/validation";
const SELECT_VALUES = [ import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
{ _id: 0.25, name: "15 seconds" }, import { useMonitorUtils } from "../../../Hooks/useMonitorUtils";
{ _id: 0.5, name: "30 seconds" }, import { useParams } from "react-router-dom";
{ _id: 1, name: "1 minute" }, import { useSelector } from "react-redux";
{ _id: 2, name: "2 minutes" }, import { useState, useEffect } from "react";
{ _id: 5, name: "5 minutes" }, import { useTheme } from "@emotion/react";
{ _id: 10, name: "10 minutes" }, import { useTranslation } from "react-i18next";
]; import {
useCreateMonitor,
const METRICS = ["cpu", "memory", "disk", "temperature"]; useDeleteMonitor,
const METRIC_PREFIX = "usage_"; useFetchGlobalSettings,
const MS_PER_MINUTE = 60000; useFetchHardwareMonitorById,
usePauseMonitor,
const hasAlertError = (errors) => { useUpdateMonitor,
return Object.keys(errors).filter((k) => k.startsWith(METRIC_PREFIX)).length > 0; } from "../../../Hooks/monitorHooks";
};
const getAlertError = (errors) => {
return Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))
? errors[Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))]
: null;
};
const CreateInfrastructureMonitor = () => { const CreateInfrastructureMonitor = () => {
const theme = useTheme();
const { user } = useSelector((state) => state.auth); const { user } = useSelector((state) => state.auth);
const { monitorId } = useParams(); const { monitorId } = useParams();
const { t } = useTranslation();
// Determine if we are creating or editing
const isCreate = typeof monitorId === "undefined"; const isCreate = typeof monitorId === "undefined";
// Fetch monitor details if editing const theme = useTheme();
const [monitor, isLoading, networkError] = useFetchHardwareMonitorById({ monitorId }); const { t } = useTranslation();
const [notifications, notificationsAreLoading, notificationsError] =
useGetNotificationsByTeamId();
const [updateMonitor, isUpdating] = useUpdateMonitor();
const [createMonitor, isCreating] = useCreateMonitor();
const [globalSettings, globalSettingsLoading] = useFetchGlobalSettings();
// State // State
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const [https, setHttps] = useState(false); const [https, setHttps] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const [updateTrigger, setUpdateTrigger] = useState(false);
const [infrastructureMonitor, setInfrastructureMonitor] = useState({ const [infrastructureMonitor, setInfrastructureMonitor] = useState({
url: "", url: "",
name: "", name: "",
@@ -90,8 +63,50 @@ const CreateInfrastructureMonitor = () => {
secret: "", secret: "",
}); });
// Populate form fields if editing // Fetch monitor details if editing
const { statusColor, pagespeedStatusMsg, determineState } = useMonitorUtils();
const [monitor, isLoading] = useFetchHardwareMonitorById({
monitorId,
updateTrigger,
});
const [createMonitor, isCreating] = useCreateMonitor();
const [deleteMonitor, isDeleting] = useDeleteMonitor();
const [globalSettings, globalSettingsLoading] = useFetchGlobalSettings();
const [notifications, notificationsAreLoading] = useGetNotificationsByTeamId();
const [pauseMonitor, isPausing] = usePauseMonitor();
const [updateMonitor, isUpdating] = useUpdateMonitor();
const FREQUENCIES = [
{ _id: 0.25, name: t("time.fifteenSeconds") },
{ _id: 0.5, name: t("time.thirtySeconds") },
{ _id: 1, name: t("time.oneMinute") },
{ _id: 2, name: t("time.twoMinutes") },
{ _id: 5, name: t("time.fiveMinutes") },
{ _id: 10, name: t("time.tenMinutes") },
];
const CRUMBS = [
{ name: "Infrastructure monitors", path: "/infrastructure" },
...(isCreate
? [{ name: "Create", path: "/infrastructure/create" }]
: [
{ name: "Details", path: `/infrastructure/${monitorId}` },
{ name: "Configure", path: `/infrastructure/configure/${monitorId}` },
]),
];
const METRICS = ["cpu", "memory", "disk", "temperature"];
const METRIC_PREFIX = "usage_";
const MS_PER_MINUTE = 60000;
const hasAlertError = (errors) => {
return Object.keys(errors).filter((k) => k.startsWith(METRIC_PREFIX)).length > 0;
};
const getAlertError = (errors) => {
const errorKey = Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX));
return errorKey ? errors[errorKey] : null;
};
// Populate form fields if editing
useEffect(() => { useEffect(() => {
if (isCreate) { if (isCreate) {
if (globalSettingsLoading) return; if (globalSettingsLoading) return;
@@ -231,6 +246,10 @@ const CreateInfrastructureMonitor = () => {
: await updateMonitor({ monitor: form, redirect: "/infrastructure" }); : await updateMonitor({ monitor: form, redirect: "/infrastructure" });
}; };
const triggerUpdate = () => {
setUpdateTrigger(!updateTrigger);
};
const onChange = (event) => { const onChange = (event) => {
const { value, name } = event.target; const { value, name } = event.target;
setInfrastructureMonitor({ setInfrastructureMonitor({
@@ -257,19 +276,26 @@ const CreateInfrastructureMonitor = () => {
}); });
}; };
const handlePause = async () => {
await pauseMonitor({ monitorId, triggerUpdate });
};
const handleRemove = async (event) => {
event.preventDefault();
await deleteMonitor({ monitor, redirect: "/infrastructure" });
};
const isBusy =
isLoading ||
isUpdating ||
isCreating ||
isDeleting ||
isPausing ||
notificationsAreLoading;
return ( return (
<Box className="create-infrastructure-monitor"> <Box className="create-infrastructure-monitor">
<Breadcrumbs <Breadcrumbs list={CRUMBS} />
list={[
{ name: "Infrastructure monitors", path: "/infrastructure" },
...(isCreate
? [{ name: "Create", path: "/infrastructure/create" }]
: [
{ name: "Details", path: `/infrastructure/${monitorId}` },
{ name: "Configure", path: `/infrastructure/configure/${monitorId}` },
]),
]}
/>
<Stack <Stack
component="form" component="form"
onSubmit={onSubmit} onSubmit={onSubmit}
@@ -278,25 +304,139 @@ const CreateInfrastructureMonitor = () => {
gap={theme.spacing(12)} gap={theme.spacing(12)}
mt={theme.spacing(6)} mt={theme.spacing(6)}
> >
<Typography <Stack
component="h1" direction="row"
variant="h1" gap={theme.spacing(2)}
> >
<Typography <Box>
component="span" <Typography
fontSize="inherit" component="h1"
> variant="h1"
{t(isCreate ? "infrastructureCreateYour" : "infrastructureEditYour")}{" "} >
</Typography> <Typography
<Typography component="span"
component="span" fontSize="inherit"
variant="h2" color={
fontSize="inherit" !isCreate ? theme.palette.primary.contrastTextSecondary : undefined
fontWeight="inherit" }
> >
{t("monitor")} {!isCreate ? infrastructureMonitor.name : t("createYour") + " "}
</Typography> </Typography>
</Typography> {isCreate ? (
<Typography
component="span"
fontSize="inherit"
fontWeight="inherit"
color={theme.palette.primary.contrastTextSecondary}
>
{t("monitor")}
</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] },
},
],
},
}}
>
<Box>
<PulseDot color={statusColor[determineState(monitor)]} />
</Box>
</Tooltip>
<Typography
component="h2"
variant="monitorUrl"
>
{infrastructureMonitor.url?.replace(/^https?:\/\//, "") || "..."}
</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")}
</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,
},
},
}}
>
{monitor?.isActive ? (
<>
<PauseCircleOutlineIcon />
{t("pause")}
</>
) : (
<>
<PlayCircleOutlineRoundedIcon />
{t("resume")}
</>
)}
</Button>
<Button
loading={isBusy}
variant="contained"
color="error"
onClick={() => setIsOpen(true)}
sx={{ ml: theme.spacing(6) }}
>
{t("remove")}
</Button>
</Box>
)}
</Stack>
<ConfigBox> <ConfigBox>
<Stack> <Stack>
<Typography <Typography
@@ -462,7 +602,7 @@ const CreateInfrastructureMonitor = () => {
label="Check frequency" label="Check frequency"
value={infrastructureMonitor.interval || 15} value={infrastructureMonitor.interval || 15}
onChange={onChange} onChange={onChange}
items={SELECT_VALUES} items={FREQUENCIES}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
@@ -474,12 +614,23 @@ const CreateInfrastructureMonitor = () => {
type="submit" type="submit"
variant="contained" variant="contained"
color="accent" color="accent"
loading={isLoading || isUpdating || isCreating || notificationsAreLoading} loading={isBusy}
> >
{t(isCreate ? "infrastructureCreateMonitor" : "infrastructureEditMonitor")} {t(isCreate ? "infrastructureCreateMonitor" : "infrastructureEditMonitor")}
</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}
/>
)}
</Box> </Box>
); );
}; };
+2
View File
@@ -980,6 +980,7 @@
"testLocale": "testLocale", "testLocale": "testLocale",
"testNotificationsDisabled": "There are no notifications setup for this monitor. You need to add one by clicking 'Configure' button", "testNotificationsDisabled": "There are no notifications setup for this monitor. You need to add one by clicking 'Configure' button",
"time": { "time": {
"fifteenSeconds": "15 seconds",
"fiveMinutes": "5 minutes", "fiveMinutes": "5 minutes",
"fourMinutes": "4 minutes", "fourMinutes": "4 minutes",
"oneDay": "1 day", "oneDay": "1 day",
@@ -987,6 +988,7 @@
"oneMinute": "1 minute", "oneMinute": "1 minute",
"oneWeek": "1 week", "oneWeek": "1 week",
"tenMinutes": "10 minutes", "tenMinutes": "10 minutes",
"thirtySeconds": "30 seconds",
"threeMinutes": "3 minutes", "threeMinutes": "3 minutes",
"twentyMinutes": "20 minutes", "twentyMinutes": "20 minutes",
"twoMinutes": "2 minutes" "twoMinutes": "2 minutes"