extract server

This commit is contained in:
Alex Holliday committed 2025-02-17 19:08:36 -08:00
1 parent 93588cfa3f
commit 24736a7bc1
531 files changed
+49 -34690

No files matched your search

@@ -0,0 +1,106 @@
// Components
import { Stack, Typography } from "@mui/material";
import ReorderRoundedIcon from "@mui/icons-material/ReorderRounded";
import DeleteIcon from "@mui/icons-material/Delete";
// Utils
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import { useTheme } from "@emotion/react";
const MonitorListItem = ({
monitor,
innerRef,
draggableProps,
dragHandleProps,
onDelete,
}) => {
const theme = useTheme();
return (
<Stack
direction={"row"}
{...draggableProps}
{...dragHandleProps}
ref={innerRef}
gap={theme.spacing(4)}
margin={theme.spacing(4)}
padding={theme.spacing(4)}
borderRadius={theme.shape.borderRadius}
alignItems={"center"}
justifyContent={"start"}
border={`1px solid ${theme.palette.primary.lowContrast}`}
>
<ReorderRoundedIcon />
<Typography>{monitor.name}</Typography>
<DeleteIcon
sx={{ marginLeft: "auto" }}
onClick={() => {
onDelete(monitor);
}}
/>
</Stack>
);
};
const MonitorList = ({ selectedMonitors, setSelectedMonitors }) => {
const onDelete = (monitorToDelete) => {
const newMonitors = selectedMonitors.filter(
(monitor) => monitor._id !== monitorToDelete._id
);
setSelectedMonitors(newMonitors);
};
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const onDragEnd = (result) => {
// dropped outside the list
if (!result.destination) {
return;
}
const reorderedMonitors = reorder(
selectedMonitors,
result.source.index,
result.destination.index
);
setSelectedMonitors(reorderedMonitors);
};
return (
<DragDropContext onDragEnd={onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<Stack
{...provided.droppableProps}
ref={provided.innerRef}
>
{selectedMonitors?.map((monitor, index) => (
<Draggable
key={monitor._id}
draggableId={monitor._id}
index={index}
>
{(provided, snapshot) => (
<MonitorListItem
monitor={monitor}
innerRef={provided.innerRef}
draggableProps={provided.draggableProps}
dragHandleProps={provided.dragHandleProps}
onDelete={onDelete}
/>
)}
</Draggable>
))}
{provided.placeholder}
</Stack>
)}
</Droppable>
</DragDropContext>
);
};
export default MonitorList;
@@ -0,0 +1,37 @@
import { Button, Box } from "@mui/material";
import ProgressUpload from "../../../../../Components/ProgressBars";
import ImageIcon from "@mui/icons-material/Image";
import { formatBytes } from "../../../../../Utils/fileUtils";
const Progress = ({ isLoading, progressValue, logo, logoType, removeLogo, errors }) => {
if (isLoading) {
return (
<ProgressUpload
icon={<ImageIcon />}
label={logo?.name}
size={formatBytes(logo?.size)}
progress={progressValue}
onClick={removeLogo}
/>
);
}
if (logo && logoType) {
return (
<Box
width="fit-content"
alignSelf="center"
>
<Button
variant="contained"
color="secondary"
onClick={removeLogo}
>
Remove Logo
</Button>
</Box>
);
}
};
export default Progress;
@@ -0,0 +1,14 @@
import { Stack, Skeleton } from "@mui/material";
const SkeletonLayout = () => {
return (
<Stack>
<Skeleton
variant="rectangular"
height={"90vh"}
/>
</Stack>
);
};
export default SkeletonLayout;
@@ -0,0 +1,104 @@
// Components
import { Stack, Typography, Button } from "@mui/material";
import { TabPanel } from "@mui/lab";
import ConfigBox from "../../../../../Components/ConfigBox";
import MonitorList from "../MonitorList";
import Search from "../../../../../Components/Inputs/Search";
import Checkbox from "../../../../../Components/Inputs/Checkbox";
// Utils
import { useState } from "react";
import { useTheme } from "@emotion/react";
const Content = ({
tabValue,
form,
monitors,
handleFormChange,
errors,
selectedMonitors,
setSelectedMonitors,
}) => {
// Local state
const [search, setSearch] = useState("");
// Handlers
const handleMonitorsChange = (selectedMonitors) => {
handleFormChange({
target: { name: "monitors", value: selectedMonitors.map((monitor) => monitor._id) },
});
setSelectedMonitors(selectedMonitors);
};
// Utils
const theme = useTheme();
return (
<TabPanel value={tabValue}>
<Stack gap={theme.spacing(10)}>
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">Status page servers</Typography>
<Typography component="p">
You can add any number of servers that you monitor to your status page. You
can also reorder them for the best viewing experience.
</Typography>
</Stack>
<Stack>
<Stack
direction="row"
justifyContent="space-between"
>
<Search
options={monitors}
multiple={true}
filteredBy="name"
value={selectedMonitors}
inputValue={search}
handleInputChange={setSearch}
handleChange={handleMonitorsChange}
/>
</Stack>
<Typography
component="span"
className="input-error"
color={theme.palette.error.main}
sx={{
opacity: 0.8,
}}
>
{errors["monitors"]}
</Typography>
<MonitorList
selectedMonitors={selectedMonitors}
setSelectedMonitors={handleMonitorsChange}
/>
</Stack>
</ConfigBox>{" "}
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">Features</Typography>
<Typography component="p">Show more details on the status page</Typography>
</Stack>
<Stack sx={{ margin: theme.spacing(6) }}>
<Checkbox
id="showCharts"
name="showCharts"
label={`Show charts`}
isChecked={form.showCharts}
onChange={handleFormChange}
/>
<Checkbox
id="showUptimePercentage"
name="showUptimePercentage"
label={`Show uptime percentage`}
isChecked={form.showUptimePercentage}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
</Stack>
<Stack gap={theme.spacing(6)}></Stack>
</TabPanel>
);
};
export default Content;
@@ -0,0 +1,142 @@
// Components
import { Stack, Typography } from "@mui/material";
import { TabPanel } from "@mui/lab";
import ConfigBox from "../../../../../Components/ConfigBox";
import Checkbox from "../../../../../Components/Inputs/Checkbox";
import TextInput from "../../../../../Components/Inputs/TextInput";
import Select from "../../../../../Components/Inputs/Select";
import ImageField from "../../../../../Components/Inputs/Image";
import ColorPicker from "../../../../../Components/Inputs/ColorPicker";
import Progress from "../Progress";
// Utils
import { useTheme } from "@emotion/react";
import timezones from "../../../../../Utils/timezones.json";
import PropTypes from "prop-types";
const TabSettings = ({
isCreate,
tabValue,
form,
handleFormChange,
handleImageChange,
progress,
removeLogo,
errors,
}) => {
// Utils
const theme = useTheme();
return (
<TabPanel value={tabValue}>
<Stack gap={theme.spacing(10)}>
<ConfigBox>
<Stack>
<Typography component="h2">Access</Typography>
<Typography component="p">
If your status page is ready, you can mark it as published.
</Typography>
</Stack>
<Stack gap={theme.spacing(18)}>
<Checkbox
id="publish"
name="isPublished"
label={`Published and visible to the public`}
isChecked={form.isPublished}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">Basic Information</Typography>
<Typography component="p">
Define company name and the subdomain that your status page points to.
</Typography>
</Stack>
<Stack gap={theme.spacing(18)}>
<TextInput
id="companyName"
name="companyName"
type="text"
label="Company name"
value={form.companyName}
onChange={handleFormChange}
helperText={errors["companyName"]}
error={errors["companyName"] ? true : false}
/>
<TextInput
id="url"
name="url"
type="url"
disabled={!isCreate}
label="Your status page address"
value={form.url}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">Timezone</Typography>
<Typography component="p">
Select the timezone that your status page will be displayed in.
</Typography>
</Stack>
<Stack gap={theme.spacing(6)}>
<Select
id="timezone"
name="timezone"
label="Display timezone"
items={timezones}
value={form.timezone}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Stack gap={theme.spacing(6)}>
<Typography component="h2">Appearance</Typography>
<Typography component="p">
Define the default look and feel of your public status page.
</Typography>
</Stack>
<Stack gap={theme.spacing(6)}>
<ImageField
id="logo"
src={form?.logo?.src}
isRound={false}
onChange={handleImageChange}
/>
<Progress
isLoading={progress.isLoading}
progressValue={progress.value}
logo={form.logo}
logoType={form.logo?.type}
removeLogo={removeLogo}
/>
<ColorPicker
id="color"
name="color"
value={form.color}
onChange={handleFormChange}
/>
</Stack>
</ConfigBox>
</Stack>
</TabPanel>
);
};
TabSettings.propTypes = {
isCreate: PropTypes.bool,
tabValue: PropTypes.string,
form: PropTypes.object,
handleFormChange: PropTypes.func,
handleImageChange: PropTypes.func,
progress: PropTypes.object,
removeLogo: PropTypes.func,
errors: PropTypes.object,
};
export default TabSettings;
@@ -0,0 +1,83 @@
// Components
import { TabContext, TabList } from "@mui/lab";
import { Tab } from "@mui/material";
import Settings from "./Settings";
import Content from "./Content";
// Utils
import PropTypes from "prop-types";
const Tabs = ({
isCreate,
form,
errors,
monitors,
selectedMonitors,
setSelectedMonitors,
handleFormChange,
handleImageChange,
progress,
removeLogo,
tab,
setTab,
TAB_LIST,
}) => {
return (
<TabContext value={TAB_LIST[tab]}>
<TabList
onChange={(_, tab) => {
setTab(TAB_LIST.indexOf(tab));
}}
>
{TAB_LIST.map((tab, idx) => {
return (
<Tab
key={tab}
label={TAB_LIST[idx]}
value={TAB_LIST[idx]}
/>
);
})}
</TabList>
{tab === 0 ? (
<Settings
tabValue={TAB_LIST[0]}
form={form}
handleFormChange={handleFormChange}
handleImageChange={handleImageChange}
progress={progress}
removeLogo={removeLogo}
errors={errors}
isCreate={isCreate}
/>
) : (
<Content
tabValue={TAB_LIST[1]}
form={form}
monitors={monitors}
handleFormChange={handleFormChange}
errors={errors}
selectedMonitors={selectedMonitors}
setSelectedMonitors={setSelectedMonitors}
/>
)}
</TabContext>
);
};
Tabs.propTypes = {
form: PropTypes.object,
errors: PropTypes.object,
monitors: PropTypes.array,
selectedMonitors: PropTypes.array,
setSelectedMonitors: PropTypes.func,
handleFormChange: PropTypes.func,
handleImageChange: PropTypes.func,
progress: PropTypes.object,
removeLogo: PropTypes.func,
tab: PropTypes.number,
setTab: PropTypes.func,
TAB_LIST: PropTypes.array,
};
export default Tabs;
@@ -0,0 +1,28 @@
import { useState } from "react";
import { networkService } from "../../../../main";
import { useSelector } from "react-redux";
import { createToast } from "../../../../Utils/toastUtils";
const useCreateStatusPage = (isCreate, url) => {
const { authToken, user } = useSelector((state) => state.auth);
const [isLoading, setIsLoading] = useState(false);
const [networkError, setNetworkError] = useState(false);
const createStatusPage = async ({ form }) => {
setIsLoading(true);
try {
await networkService.createStatusPage({ authToken, user, form, isCreate, url });
return true;
} catch (error) {
setNetworkError(true);
createToast({ body: error?.response?.data?.msg ?? error.message });
return false;
} finally {
setIsLoading(false);
}
};
return [createStatusPage, isLoading, networkError];
};
export { useCreateStatusPage };
@@ -0,0 +1,35 @@
import { useEffect, useState } from "react";
import { networkService } from "../../../../main";
import { useSelector } from "react-redux";
import { createToast } from "../../../../Utils/toastUtils";
const useMonitorsFetch = () => {
const { user, authToken } = useSelector((state) => state.auth);
const [monitors, setMonitors] = useState(undefined);
const [isLoading, setIsLoading] = useState(true);
const [networkError, setNetworkError] = useState(false);
useEffect(() => {
const fetchMonitors = async () => {
try {
const response = await networkService.getMonitorsByTeamId({
authToken: authToken,
teamId: user.teamId,
limit: null, // donot return any checks for the monitors
types: ["http"], // status page is available only for the uptime type
});
setMonitors(response.data.data.monitors);
} catch (error) {
setNetworkError(true);
createToast({ body: error.message });
} finally {
setIsLoading(false);
}
};
fetchMonitors();
}, [authToken, user]);
return [monitors, isLoading, networkError];
};
export { useMonitorsFetch };
+251
View File
@@ -0,0 +1,251 @@
// Components
import { Stack, Button, Typography } from "@mui/material";
import Tabs from "./Components/Tabs";
import GenericFallback from "../../../Components/GenericFallback";
import SkeletonLayout from "./Components/Skeleton";
//Utils
import { useTheme } from "@emotion/react";
import { useState, useEffect, useRef, useCallback } from "react";
import { statusPageValidation } from "../../../Validation/validation";
import { buildErrors } from "../../../Validation/error";
import { useMonitorsFetch } from "./Hooks/useMonitorsFetch";
import { useCreateStatusPage } from "./Hooks/useCreateStatusPage";
import { createToast } from "../../../Utils/toastUtils";
import { useNavigate } from "react-router-dom";
import { useStatusPageFetch } from "../Status/Hooks/useStatusPageFetch";
import { useParams } from "react-router-dom";
//Constants
const TAB_LIST = ["General settings", "Contents"];
const ERROR_TAB_MAPPING = [
["companyName", "url", "timezone", "color", "isPublished", "logo"],
["monitors", "showUptimePercentage", "showCharts"],
];
const CreateStatusPage = () => {
const { url } = useParams();
//Local state
const [tab, setTab] = useState(0);
const [progress, setProgress] = useState({ value: 0, isLoading: false });
const [form, setForm] = useState({
isPublished: false,
companyName: "",
url: url ?? Math.floor(Math.random() * 1000000).toFixed(0),
logo: undefined,
timezone: "America/Toronto",
color: "#4169E1",
type: "uptime",
monitors: [],
showCharts: true,
showUptimePercentage: true,
});
const [errors, setErrors] = useState({});
const [selectedMonitors, setSelectedMonitors] = useState([]);
// Refs
const intervalRef = useRef(null);
// Setup
const isCreate = typeof url === "undefined";
//Utils
const theme = useTheme();
const [monitors, isLoading, networkError] = useMonitorsFetch();
const [createStatusPage, createStatusIsLoading, createStatusPageNetworkError] =
useCreateStatusPage(isCreate);
const navigate = useNavigate();
const [statusPage, statusPageMonitors, statusPageIsLoading, statusPageNetworkError] =
useStatusPageFetch(isCreate, url);
// Handlers
const handleFormChange = (e) => {
let { type, name, value, checked } = e.target;
// Handle errors
const { error } = statusPageValidation.validate(
{ [name]: value },
{ abortEarly: false }
);
setErrors((prev) => {
return buildErrors(prev, name, error);
});
//Handle checkbox
if (type === "checkbox") {
setForm((prev) => ({
...prev,
[name]: checked,
}));
return;
}
// Handle other inputs
setForm((prev) => ({
...prev,
[name]: value,
}));
};
const handleImageChange = useCallback((event) => {
const img = event.target?.files?.[0];
const newLogo = {
src: URL.createObjectURL(img),
name: img.name,
type: img.type,
size: img.size,
};
setForm((prev) => ({
...prev,
logo: newLogo,
}));
intervalRef.current = setInterval(() => {
const buffer = 12;
setProgress((prev) => {
if (prev.value + buffer >= 100) {
clearInterval(intervalRef.current);
return { value: 100, isLoading: false };
}
return { ...prev, value: prev.value + buffer };
});
}, 120);
}, []);
const removeLogo = () => {
setForm((prev) => ({
...prev,
logo: undefined,
}));
// interrupt interval if image upload is canceled prior to completing the process
clearInterval(intervalRef.current);
setProgress({ value: 0, isLoading: false });
};
const handleSubmit = async () => {
let toSubmit = {
...form,
logo: { type: form.logo?.type ?? null, size: form.logo?.size ?? null },
};
const { error } = statusPageValidation.validate(toSubmit, {
abortEarly: false,
});
if (typeof error === "undefined") {
const success = await createStatusPage({ form });
if (success) {
createToast({
body: isCreate
? "Status page created successfully"
: "Status page updated successfully",
});
navigate(`/status/uptime/${form.url}`);
}
return;
}
const newErrors = {};
error?.details?.forEach((err) => {
newErrors[err.path[0]] = err.message;
});
setErrors((prev) => ({ ...prev, ...newErrors }));
const errorTabs = Object.keys(newErrors).map((err) => {
return ERROR_TAB_MAPPING.findIndex((tab) => tab.includes(err));
});
// If there's an error in the current tab, don't change the tab
if (errorTabs.some((errorTab) => errorTab === tab)) {
return;
}
// If we get -1, there's an unknown error
if (errorTabs[0] === -1) {
createToast({ body: "Unknown error" });
return;
}
// Otherwise go to tab with error
setTab(errorTabs[0]);
};
// If we are configuring, populate fields
useEffect(() => {
if (isCreate) return;
if (typeof statusPage === "undefined") {
return;
}
let newLogo = undefined;
if (statusPage.logo) {
newLogo = {
src: `data:${statusPage.logo.contentType};base64,${statusPage.logo.data}`,
name: "logo",
type: statusPage.logo.contentType,
size: null,
};
}
setForm((prev) => {
return {
...prev,
companyName: statusPage?.companyName,
isPublished: statusPage?.isPublished,
timezone: statusPage?.timezone,
monitors: statusPageMonitors.map((monitor) => monitor._id),
color: statusPage?.color,
logo: newLogo,
};
});
setSelectedMonitors(statusPageMonitors);
}, [isCreate, statusPage, statusPageMonitors]);
if (networkError === true) {
return (
<GenericFallback>
<Typography
variant="h1"
marginY={theme.spacing(4)}
color={theme.palette.primary.contrastTextTertiary}
>
Network error
</Typography>
<Typography>Please check your connection</Typography>
</GenericFallback>
);
}
if (isLoading) return <SkeletonLayout />;
// Load fields
return (
<Stack gap={theme.spacing(10)}>
<Tabs
form={form}
errors={errors}
monitors={monitors}
selectedMonitors={selectedMonitors}
setSelectedMonitors={setSelectedMonitors}
handleFormChange={handleFormChange}
handleImageChange={handleImageChange}
progress={progress}
removeLogo={removeLogo}
tab={tab}
setTab={setTab}
TAB_LIST={TAB_LIST}
isCreate={isCreate}
/>
<Stack
direction="row"
justifyContent="flex-end"
>
<Button
variant="contained"
color="accent"
onClick={handleSubmit}
>
Save
</Button>
</Stack>
</Stack>
);
};
export default CreateStatusPage;
@@ -0,0 +1,34 @@
// Components
import { Box, Typography } from "@mui/material";
// Utils
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
const AdminLink = () => {
const theme = useTheme();
const navigate = useNavigate();
return (
<Box>
<Typography
className="forgot-p"
display="inline-block"
color={theme.palette.primary.contrastText}
>
Administrator?
</Typography>
<Typography
component="span"
color={theme.palette.accent.main}
ml={theme.spacing(2)}
sx={{ cursor: "pointer" }}
onClick={() => navigate("/login")}
>
Login here
</Typography>
</Box>
);
};
export default AdminLink;
@@ -0,0 +1,129 @@
// Components
import { Box, Stack, Typography, Button } from "@mui/material";
import Image from "../../../../../Components/Image";
import SettingsIcon from "../../../../../assets/icons/settings-bold.svg?react";
//Utils
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-router-dom";
import PropTypes from "prop-types";
const Controls = ({ isDeleteOpen, setIsDeleteOpen, isDeleting, url, type }) => {
const theme = useTheme();
const location = useLocation();
const currentPath = location.pathname;
const navigate = useNavigate();
if (currentPath.startsWith("/status/uptime/public")) {
return null;
}
if (currentPath.startsWith("/status/distributed/public")) {
return null;
}
return (
<Stack
direction="row"
gap={theme.spacing(2)}
>
<Box>
<Button
variant="contained"
color="error"
onClick={() => setIsDeleteOpen(!isDeleteOpen)}
loading={isDeleting}
>
Delete
</Button>
</Box>
<Box>
<Button
variant="contained"
color="secondary"
onClick={() => {
if (type === "uptime") {
navigate(`/status/uptime/configure/${url}`);
} else {
navigate(`/status/distributed/configure/${url}`);
}
}}
sx={{
px: theme.spacing(5),
"& svg": {
mr: theme.spacing(3),
"& path": {
stroke: theme.palette.secondary.contrastText,
},
},
}}
>
<SettingsIcon /> Configure
</Button>
</Box>
</Stack>
);
};
Controls.propTypes = {
type: PropTypes.string,
isDeleting: PropTypes.bool,
url: PropTypes.string,
isDeleteOpen: PropTypes.bool.isRequired,
setIsDeleteOpen: PropTypes.func.isRequired,
};
const ControlsHeader = ({
statusPage,
isDeleting,
isDeleteOpen,
setIsDeleteOpen,
url,
type = "uptime",
}) => {
const theme = useTheme();
return (
<Stack
alignSelf="flex-start"
direction="row"
width="100%"
gap={theme.spacing(2)}
justifyContent="space-between"
alignItems="flex-end"
>
<Stack
direction="row"
gap={theme.spacing(8)}
alignItems="flex-end"
>
<Image
shouldRender={statusPage?.logo?.data ? true : false}
alt={"Company logo"}
maxWidth={"300px"}
base64={statusPage?.logo?.data}
/>
<Typography variant="h2">{statusPage?.companyName}</Typography>
</Stack>
<Controls
isDeleting={isDeleting}
isDeleteOpen={isDeleteOpen}
setIsDeleteOpen={setIsDeleteOpen}
url={url}
type={type}
/>
</Stack>
);
};
ControlsHeader.propTypes = {
url: PropTypes.string,
statusPage: PropTypes.object,
isDeleting: PropTypes.bool,
isDeleteOpen: PropTypes.bool.isRequired,
setIsDeleteOpen: PropTypes.func.isRequired,
type: PropTypes.string,
};
export default ControlsHeader;
@@ -0,0 +1,58 @@
// Components
import { Stack, Box } from "@mui/material";
import Host from "../../../../../Components/Host";
import StatusPageBarChart from "../../../../../Components/Charts/StatusPageBarChart";
import { StatusLabel } from "../../../../../Components/Label";
//Utils
import { useTheme } from "@mui/material/styles";
import useUtils from "../../../../Uptime/Monitors/Hooks/useUtils";
import PropTypes from "prop-types";
const MonitorsList = ({ monitors = [] }) => {
const theme = useTheme();
const { determineState } = useUtils();
return (
<>
{monitors?.map((monitor) => {
const status = determineState(monitor);
return (
<Stack
key={monitor._id}
width="100%"
gap={theme.spacing(2)}
>
<Host
key={monitor._id}
url={monitor.url}
title={monitor.title}
percentageColor={monitor.percentageColor}
percentage={monitor.percentage}
/>
<Stack
direction="row"
alignItems="center"
gap={theme.spacing(20)}
>
<Box flex={9}>
<StatusPageBarChart checks={monitor?.checks?.slice().reverse()} />
</Box>
<Box flex={1}>
<StatusLabel
status={status}
text={status}
customStyles={{ textTransform: "capitalize" }}
/>
</Box>
</Stack>
</Stack>
);
})}
</>
);
};
MonitorsList.propTypes = {
monitors: PropTypes.array.isRequired,
};
export default MonitorsList;
@@ -0,0 +1,14 @@
import { Stack, Skeleton } from "@mui/material";
const SkeletonLayout = () => {
return (
<Stack>
<Skeleton
variant="rectangular"
height={"90vh"}
/>
</Stack>
);
};
export default SkeletonLayout;
@@ -0,0 +1,74 @@
// Components
import { Stack, Typography } from "@mui/material";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";
// Utils
import { useTheme } from "@mui/material/styles";
import PropTypes from "prop-types";
const getMonitorStatus = (monitors, theme) => {
const monitorsStatus = {
icon: (
<ErrorOutlineIcon
sx={{ color: theme.palette.primary.contrastTextSecondaryDarkBg }}
/>
),
};
if (monitors.every((monitor) => monitor.status === true)) {
monitorsStatus.msg = "All systems operational";
monitorsStatus.color = theme.palette.success.lowContrast;
monitorsStatus.icon = (
<CheckCircleIcon
sx={{ color: theme.palette.primary.contrastTextSecondaryDarkBg }}
/>
);
}
if (monitors.every((monitor) => monitor.status === false)) {
monitorsStatus.msg = "All systems down";
monitorsStatus.color = theme.palette.error.lowContrast;
}
if (monitors.some((monitor) => monitor.status === false)) {
monitorsStatus.msg = "Degraded performance";
monitorsStatus.color = theme.palette.warning.lowContrast;
}
// Paused or unknown
if (monitors.some((monitor) => typeof monitor.status === "undefined")) {
monitorsStatus.msg = "Unknown status";
monitorsStatus.color = theme.palette.warning.lowContrast;
}
return monitorsStatus;
};
const StatusBar = ({ monitors }) => {
const theme = useTheme();
if (typeof monitors === "undefined") return;
const monitorsStatus = getMonitorStatus(monitors, theme);
return (
<Stack
direction="row"
alignItems="center"
justifyContent="center"
gap={theme.spacing(2)}
height={theme.spacing(30)}
width={"100%"}
backgroundColor={monitorsStatus.color}
borderRadius={theme.spacing(2)}
>
{monitorsStatus.icon}
{/* CAIO_REVIEW */}
<Typography variant="h2DarkBg">{monitorsStatus.msg}</Typography>
</Stack>
);
};
export default StatusBar;
StatusBar.propTypes = {
status: PropTypes.object,
};
@@ -0,0 +1,28 @@
import { useSelector } from "react-redux";
import { useState } from "react";
import { networkService } from "../../../../main";
import { createToast } from "../../../../Utils/toastUtils";
const useStatusPageDelete = (fetchStatusPage, url) => {
const [isLoading, setIsLoading] = useState(false);
const { authToken } = useSelector((state) => state.auth);
const deleteStatusPage = async () => {
try {
setIsLoading(true);
await networkService.deleteStatusPage({ authToken, url });
fetchStatusPage?.();
return true;
} catch (error) {
createToast({
body: error.message,
});
return false;
} finally {
setIsLoading(false);
}
};
return [deleteStatusPage, isLoading];
};
export { useStatusPageDelete };
@@ -0,0 +1,55 @@
import { useEffect, useState, useCallback } from "react";
import { networkService } from "../../../../main";
import { useSelector } from "react-redux";
import { createToast } from "../../../../Utils/toastUtils";
import { useTheme } from "@emotion/react";
import { useMonitorUtils } from "../../../../Hooks/useMonitorUtils";
const useStatusPageFetch = (isCreate = false, url) => {
const [isLoading, setIsLoading] = useState(true);
const [networkError, setNetworkError] = useState(false);
const [statusPage, setStatusPage] = useState(undefined);
const [monitors, setMonitors] = useState(undefined);
const { authToken } = useSelector((state) => state.auth);
const theme = useTheme();
const { getMonitorWithPercentage } = useMonitorUtils();
const fetchStatusPage = useCallback(async () => {
try {
const response = await networkService.getStatusPageByUrl({
authToken,
url,
type: "uptime",
});
if (!response?.data?.data) return;
const { statusPage, monitors } = response.data.data;
setStatusPage(statusPage);
const monitorsWithPercentage = monitors.map((monitor) =>
getMonitorWithPercentage(monitor, theme)
);
setMonitors(monitorsWithPercentage);
} catch (error) {
// If there is a 404, status page is not found
if (error?.response?.status === 404) {
setStatusPage(undefined);
return;
}
createToast({ body: error.message });
setNetworkError(true);
} finally {
setIsLoading(false);
}
}, [authToken, theme, getMonitorWithPercentage, url]);
useEffect(() => {
if (isCreate === true) {
return;
}
fetchStatusPage();
}, [isCreate, fetchStatusPage]);
return [statusPage, monitors, isLoading, networkError, fetchStatusPage];
};
export { useStatusPageFetch };
+159
View File
@@ -0,0 +1,159 @@
// Components
import { Typography, Stack } from "@mui/material";
import GenericFallback from "../../../Components/GenericFallback";
import AdminLink from "./Components/AdminLink";
import ControlsHeader from "./Components/ControlsHeader";
import SkeletonLayout from "./Components/Skeleton";
import StatusBar from "./Components/StatusBar";
import MonitorsList from "./Components/MonitorsList";
import Dialog from "../../../Components/Dialog";
// Utils
import { useStatusPageFetch } from "./Hooks/useStatusPageFetch";
import { useTheme } from "@emotion/react";
import { useIsAdmin } from "../../../Hooks/useIsAdmin";
import { useLocation } from "react-router-dom";
import { useStatusPageDelete } from "./Hooks/useStatusPageDelete";
import { useState } from "react";
import { useParams } from "react-router-dom";
import { useNavigate } from "react-router-dom";
const PublicStatus = () => {
const { url } = useParams();
// Local state
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
// Utils
const theme = useTheme();
const isAdmin = useIsAdmin();
const location = useLocation();
const navigate = useNavigate();
const [statusPage, monitors, isLoading, networkError, fetchStatusPage] =
useStatusPageFetch(false, url);
const [deleteStatusPage, isDeleting] = useStatusPageDelete(fetchStatusPage, url);
// Setup
const currentPath = location.pathname;
let sx = { paddingLeft: theme.spacing(20), paddingRight: theme.spacing(20) };
let link = undefined;
const isPublic = location.pathname.startsWith("/status/uptime/public");
// Public status page
if (isPublic) {
sx = {
paddingTop: theme.spacing(20),
paddingLeft: "20vw",
paddingRight: "20vw",
};
link = <AdminLink />;
}
// Loading
if (isLoading) {
return <SkeletonLayout />;
}
// Error fetching data
if (networkError === true) {
return (
<GenericFallback>
<Typography
variant="h1"
marginY={theme.spacing(4)}
color={theme.palette.primary.contrastTextTertiary}
>
Network error
</Typography>
<Typography>Please check your connection</Typography>
</GenericFallback>
);
}
// Public status page fallback
if (!isLoading && typeof statusPage === "undefined" && isPublic) {
return (
<Stack sx={sx}>
<GenericFallback>
<Typography
variant="h1"
marginY={theme.spacing(4)}
color={theme.palette.primary.contrastTextTertiary}
>
A public status page is not set up.
</Typography>
<Typography>Please contact to your administrator</Typography>
</GenericFallback>
</Stack>
);
}
// Finished loading, but status page is not public
if (!isLoading && isPublic && statusPage.isPublished === false) {
return (
<Stack sx={sx}>
<GenericFallback>
<Typography
variant="h1"
marginY={theme.spacing(4)}
color={theme.palette.primary.contrastTextTertiary}
>
This status page is not public.
</Typography>
<Typography>Please contact to your administrator</Typography>
</GenericFallback>
</Stack>
);
}
// Status page doesn't exist
if (!isLoading && typeof statusPage === "undefined") {
return (
<GenericFallback>
<Typography
variant="h1"
marginY={theme.spacing(4)}
color={theme.palette.primary.contrastTextTertiary}
>
There's no status page here.
</Typography>
<Typography>Please contact to your administrator</Typography>
</GenericFallback>
);
}
return (
<Stack
gap={theme.spacing(10)}
alignItems="center"
sx={{ ...sx, position: "relative" }}
>
<ControlsHeader
statusPage={statusPage}
isDeleting={isDeleting}
isDeleteOpen={isDeleteOpen}
setIsDeleteOpen={setIsDeleteOpen}
url={url}
/>
<Typography variant="h2">Service status</Typography>
<StatusBar monitors={monitors} />
<MonitorsList monitors={monitors} />
{link}
<Dialog
title="Do you want to delete this status page?"
onConfirm={() => {
deleteStatusPage();
setIsDeleteOpen(false);
navigate("/status");
}}
onCancel={() => {
setIsDeleteOpen(false);
}}
open={isDeleteOpen}
confirmationButtonLabel="Yes, delete status page"
description="Once deleted, your status page cannot be retrieved."
isLoading={isDeleting || isLoading}
/>
</Stack>
);
};
export default PublicStatus;
@@ -0,0 +1,85 @@
import DataTable from "../../../../../Components/Table";
import { useTheme } from "@emotion/react";
import { useNavigate } from "react-router-dom";
import { ColoredLabel } from "../../../../../Components/Label";
import ArrowOutwardIcon from "@mui/icons-material/ArrowOutward";
import { Stack, Typography } from "@mui/material";
const StatusPagesTable = ({ data }) => {
const theme = useTheme();
const navigate = useNavigate();
const headers = [
{
id: "name",
content: "Status page name",
render: (row) => {
return row.companyName;
},
},
{
id: "url",
content: "URL",
render: (row) => {
return (
<Stack
direction="row"
alignItems="center"
gap={theme.spacing(2)}
>
<Typography>{`/${row.url}`}</Typography>
<ArrowOutwardIcon />
</Stack>
);
},
},
{
id: "type",
content: "Type",
render: (row) => {
return row.type;
},
},
{
id: "status",
content: "Status",
render: (row) => {
return (
<ColoredLabel
label={row.isPublished ? "Published" : "Unpublished"}
color={
row.isPublished ? theme.palette.success.main : theme.palette.warning.main
}
/>
);
},
},
];
const handleRowClick = (statusPage) => {
if (statusPage.type === "distributed") {
navigate(`/status/distributed/${statusPage.url}`);
} else if (statusPage.type === "uptime") {
navigate(`/status/uptime/${statusPage.url}`);
}
};
return (
<DataTable
config={{
rowSX: {
cursor: "pointer",
"&:hover td": {
backgroundColor: theme.palette.tertiary.main,
transition: "background-color .3s ease",
},
},
onRowClick: (row) => {
handleRowClick(row);
},
}}
headers={headers}
data={data}
/>
);
};
export default StatusPagesTable;
@@ -0,0 +1,35 @@
import { useState, useEffect } from "react";
import { networkService } from "../../../../main";
import { useSelector } from "react-redux";
import { createToast } from "../../../../Utils/toastUtils";
const useStatusPagesFetch = () => {
const { authToken, user } = useSelector((state) => state.auth);
const [isLoading, setIsLoading] = useState(true);
const [networkError, setNetworkError] = useState(false);
const [statusPages, setStatusPages] = useState(undefined);
useEffect(() => {
const fetchStatusPages = async () => {
try {
const res = await networkService.getStatusPagesByTeamId({
authToken,
teamId: user.teamId,
});
setStatusPages(res?.data?.data);
} catch (error) {
setNetworkError(true);
createToast({
body: error.message,
});
} finally {
setIsLoading(false);
}
};
fetchStatusPages();
}, [authToken, user]);
return [isLoading, networkError, statusPages];
};
export { useStatusPagesFetch };
@@ -0,0 +1,67 @@
// Components
import { Stack, Typography } from "@mui/material";
import Breadcrumbs from "../../../Components/Breadcrumbs";
import Fallback from "../../../Components/Fallback";
import MonitorCreateHeader from "../../../Components/MonitorCreateHeader";
import GenericFallback from "../../../Components/GenericFallback";
import StatusPagesTable from "./Components/StatusPagesTable";
import SkeletonLayout from "../../../Components/Skeletons/FullPage";
// Utils
import { useTheme } from "@emotion/react";
import { useStatusPagesFetch } from "./Hooks/useStatusPagesFetch";
import { useIsAdmin } from "../../../Hooks/useIsAdmin";
const BREADCRUMBS = [{ name: `Status Pages`, path: "" }];
const StatusPages = () => {
// Utils
const theme = useTheme();
const isAdmin = useIsAdmin();
const [isLoading, networkError, statusPages] = useStatusPagesFetch();
if (isLoading) {
return <SkeletonLayout />;
}
if (networkError === true) {
return (
<GenericFallback>
<Typography
variant="h1"
marginY={theme.spacing(4)}
color={theme.palette.primary.contrastTextTertiary}
>
Network error
</Typography>
<Typography>Please check your connection</Typography>
</GenericFallback>
);
}
if (!isLoading && typeof statusPages !== "undefined" && statusPages.length === 0) {
return (
<Fallback
title="status page"
checks={[
"Monitor and display the health of your services in real time",
"Track multiple services and share their status",
"Keep users informed about outages and performance",
]}
link="/status/uptime/create"
isAdmin={isAdmin}
/>
);
}
return (
<Stack gap={theme.spacing(10)}>
<Breadcrumbs list={BREADCRUMBS} />
<MonitorCreateHeader
label="Create status page"
isAdmin={isAdmin}
path="/status/uptime/create"
/>
<StatusPagesTable data={statusPages} />
</Stack>
);
};
export default StatusPages;