initial commit

This commit is contained in:
Alex Holliday committed 2025-11-13 13:47:26 -08:00
1 parent 7cb985116e
commit 75acf7b38f
955 files changed
+37333 -87054

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
import { Table, Pagination, StatusLabel } from "@/components/design-elements";
import Box from "@mui/material/Box";
import type { Header } from "@/components/design-elements/Table";
import type { ICheck, IChecksWithCount } from "@/types/check";
import type { ApiResponse } from "@/hooks/UseApi";
import type { MonitorStatus } from "@/types/monitor";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useGet } from "@/hooks/UseApi";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<ICheck>[] = [
{
id: "status",
content: t("status"),
render: (row) => {
return <StatusLabel status={row.status as MonitorStatus} />;
},
},
{
id: "date",
content: t("date&Time"),
render: (row) => {
return formatDateWithTz(
row.createdAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
);
},
},
{
id: "statusCode",
content: t("statusCode"),
render: (row) => {
return row.httpStatusCode || "N/A";
},
},
];
return headers;
};
export const CheckTable = ({ monitorId }: { monitorId: string }) => {
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
const { t } = useTranslation();
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const headers = getHeaders(t, uiTimezone);
const { response, error } = useGet<ApiResponse<IChecksWithCount>>(
`/monitors/${monitorId}/checks?page=${page}&rowsPerPage=${rowsPerPage}`,
{},
{ keepPreviousData: true }
);
const checks = response?.data?.checks || [];
const count = response?.data?.count || 0;
const handlePageChange = (
_e: React.MouseEvent<HTMLButtonElement> | null,
newPage: number
) => {
setPage(newPage);
};
const handleRowsPerPageChange = (
e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
) => {
const value = Number(e.target.value);
setPage(0);
setRowsPerPage(value);
};
if (error) {
console.error(error);
}
return (
<Box>
<Table headers={headers} data={checks} />
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
+184
View File
@@ -0,0 +1,184 @@
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Table, Pagination, StatusLabel } from "@/components/design-elements";
import { HistogramResponseTime } from "@/components/monitors";
import type { Header } from "@/components/design-elements/Table";
import { ActionsMenu } from "@/components/actions-menu";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import { usePatch } from "@/hooks/UseApi";
import type { IMonitor } from "@/types/monitor";
import type { ActionMenuItem } from "@/components/actions-menu";
export const MonitorTable = ({
monitors,
refetch,
setSelectedMonitor,
count,
page,
setPage,
rowsPerPage,
setRowsPerPage,
}: {
monitors: IMonitor[];
refetch: Function;
setSelectedMonitor: Function;
count: number;
page: number;
setPage: (page: number) => void;
rowsPerPage: number;
setRowsPerPage: (rowsPerPage: number) => void;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const navigate = useNavigate();
const {
patch,
// loading: isPatching,
// error: postError,
} = usePatch<any, IMonitor>();
const handlePageChange = (
_e: React.MouseEvent<HTMLButtonElement> | null,
newPage: number
) => {
setPage(newPage);
};
const handleRowsPerPageChange = (
e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
) => {
const value = Number(e.target.value);
setPage(0);
setRowsPerPage(value);
};
const getActions = (monitor: IMonitor): ActionMenuItem[] => {
return [
{
id: 1,
label: "Open site",
action: () => {
window.open(monitor.url, "_blank", "noreferrer");
},
closeMenu: true,
},
{
id: 2,
label: "Details",
action: () => {
navigate(`${monitor._id}`);
},
},
{
id: 3,
label: "Incidents",
action: () => {
navigate(`/incidents/${monitor._id}`);
},
},
{
id: 4,
label: "Configure",
action: () => {
navigate(`/uptime/${monitor._id}/configure`);
},
},
// {
// id: 5,
// label: "Clone",
// action: () => {
// console.log("Open clone");
// },
// },
{
id: 6,
label: monitor.isActive ? "Pause" : "Resume",
action: async () => {
await patch(`/monitors/${monitor._id}/active`);
refetch();
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: () => {
setSelectedMonitor(monitor);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<IMonitor>[] = [
{
id: "name",
content: t("host"),
render: (row) => {
return row.name;
},
},
{
id: "status",
content: t("status"),
render: (row) => {
return <StatusLabel status={row.status} isActive={row.isActive} />;
},
},
{
id: "histogram",
content: t("responseTime"),
render: (row) => {
return (
<Stack alignItems={{ xs: "flex-start", md: "center" }}>
<HistogramResponseTime checks={row.latestChecks} />
</Stack>
);
},
},
{
id: "type",
content: t("type"),
render: (row) => {
return row.type;
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
const headers = getHeaders();
return (
<Box>
<Table
headers={headers}
data={monitors}
onRowClick={(row) => {
navigate(`/uptime/${row._id}`);
}}
/>
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
@@ -0,0 +1,62 @@
import { monitorSchema } from "@/validation/zod";
import { useGet, usePatch } from "@/hooks/UseApi";
import { UptimeForm } from "@/pages/uptime/UptimeForm";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import humanInterval from "human-interval";
import { z } from "zod";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
import type { IMonitor } from "@/types/monitor";
const UptimeConfigurePage = () => {
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const { id } = useParams();
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { response: monitorResponse } = useGet<ApiResponse<IMonitor>>(
`/monitors/${id}`
);
const monitor = monitorResponse?.data || {};
const notificationOptions = response?.data ?? [];
const { patch, loading, error } = usePatch<Partial<SubmitValues>, IMonitor>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = {
type: data.type,
name: data.name,
n: data.n,
notificationChannels: data.notificationChannels,
interval,
};
const result = await patch(`/monitors/${id}`, submitData);
if (result) {
navigate(`/uptime/${id}`);
} else {
console.error(error);
}
};
return (
<UptimeForm
mode="configure"
initialData={{
...monitor,
}}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default UptimeConfigurePage;
+43
View File
@@ -0,0 +1,43 @@
import { UptimeForm } from "./UptimeForm";
import humanInterval from "human-interval";
import { z } from "zod";
import { monitorSchema } from "@/validation/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
const UptimeCreatePage = () => {
type FormValues = z.infer<typeof monitorSchema>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { post, loading, error } = usePost<SubmitValues>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = { ...data, interval };
const result = await post("/monitors", submitData);
if (result) {
navigate("/uptime");
} else {
console.error(error);
}
};
const notificationOptions = response?.data ?? [];
return (
<UptimeForm
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default UptimeCreatePage;
+162
View File
@@ -0,0 +1,162 @@
import { BasePage, StatBox } from "@/components/design-elements";
import {
HeaderControls,
HeaderRange,
HistogramStatus,
ChartAvgResponse,
ChartResponseTime,
} from "@/components/monitors";
import Stack from "@mui/material/Stack";
import { CheckTable } from "@/pages/uptime/CheckTable";
import type { IMonitor, IMonitorWithMonitorStats } from "@/types/monitor";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import { useGet, usePatch, type ApiResponse } from "@/hooks/UseApi";
import { useState } from "react";
import { getStatusPalette } from "@/utils/MonitorUtils";
import prettyMilliseconds from "pretty-ms";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const UptimeDetailsPage = () => {
const { id } = useParams();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
// Local state
const [range, setRange] = useState("2h");
const { response, isValidating, error, refetch } = useGet<
ApiResponse<IMonitorWithMonitorStats>
>(
`/monitors/${id}?embedChecks=true&range=${range}`,
{},
{ refreshInterval: GLOBAL_REFRESH, keepPreviousData: true }
);
const {
response: upResponse,
isValidating: upIsValidating,
error: upError,
} = useGet<ApiResponse<IMonitorWithMonitorStats>>(
`/monitors/${id}?embedChecks=true&range=${range}&status=up`,
{},
{ keepPreviousData: true }
);
const {
response: downResponse,
error: downError,
isValidating: downIsValidating,
} = useGet<ApiResponse<IMonitorWithMonitorStats>>(
`/monitors/${id}?embedChecks=true&range=${range}&status=down`,
{},
{ keepPreviousData: true }
);
const {
patch,
loading: isPatching,
error: postError,
} = usePatch<any, IMonitor>();
const monitor = response?.data?.monitor;
if (!monitor) {
return null;
}
const stats = response?.data?.stats || null;
const avgResponseTime = stats?.avgResponseTime || 0;
const maxResponseTime = stats?.maxResponseTime || 0;
const streakDuration = stats?.currentStreakStartedAt
? Date.now() - stats?.currentStreakStartedAt
: 0;
const lastChecked = stats?.lastCheckTimestamp
? Date.now() - stats?.lastCheckTimestamp
: -1;
const checks = response?.data?.checks || [];
const upChecks = upResponse?.data?.checks
? [...upResponse.data.checks].reverse()
: [];
const downChecks = downResponse?.data?.checks
? [...downResponse.data.checks].reverse()
: [];
const palette = getStatusPalette(monitor?.status);
if (error || upError || downError || postError) {
console.error("Error fetching monitor data:", {
error,
upError,
downError,
postError,
});
}
return (
<BasePage>
<HeaderControls
monitor={monitor}
patch={patch}
isPatching={isPatching}
refetch={refetch}
path="/uptime"
/>
<Stack direction="row" gap={theme.spacing(8)}>
<StatBox
palette={palette}
title="Active for"
subtitle={prettyMilliseconds(streakDuration, {
secondsDecimalDigits: 0,
})}
/>
<StatBox
title="Last check"
subtitle={
lastChecked >= 0
? `${prettyMilliseconds(lastChecked, {
secondsDecimalDigits: 0,
})} ago`
: "N/A"
}
/>
<StatBox
title="Last response time"
subtitle={
stats?.lastResponseTime ? `${stats?.lastResponseTime} ms` : "N/A"
}
/>
</Stack>
<HeaderRange
loading={isValidating || upIsValidating || downIsValidating}
range={range}
setRange={setRange}
/>
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(8)}>
<HistogramStatus
title="Uptime"
status={"up"}
checks={upChecks}
range={range}
/>
<HistogramStatus
title="Incidents"
checks={downChecks}
status={"down"}
range={range}
/>
<ChartAvgResponse avg={avgResponseTime} max={maxResponseTime} />
</Stack>
<ChartResponseTime checks={checks} range={range} />
<CheckTable monitorId={monitor?._id} />
</BasePage>
);
};
export default UptimeDetailsPage;
+306
View File
@@ -0,0 +1,306 @@
import Stack from "@mui/material/Stack";
import {
TextInput,
Button,
AutoComplete,
RadioWithDescription,
} from "@/components/inputs";
import { ConfigBox, BasePage } from "@/components/design-elements";
import RadioGroup from "@mui/material/RadioGroup";
import FormControl from "@mui/material/FormControl";
import { Trash2 } from "lucide-react";
import { Typography } from "@mui/material";
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchema } from "@/validation/zod";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
useForm,
Controller,
useWatch,
type SubmitHandler,
} from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitMonitorFrom";
type FormValues = z.infer<typeof monitorSchema>;
export const UptimeForm = ({
mode = "create",
initialData,
onSubmit,
notificationOptions,
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const {
handleSubmit,
control,
setValue,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchema) as any,
defaultValues: defaults,
mode: "onChange",
});
useEffect(() => {
reset(defaults);
}, [initialData, reset, defaults]);
const selectedType = useWatch({
control,
name: "type",
});
const url = useWatch({ control, name: "url" });
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
useEffect(() => {
if (!selectedType) return;
if (selectedType !== "http" && selectedType !== "https") {
setValue("url", "");
return;
}
if (selectedType !== "http" && selectedType !== "https") return;
if (!url) {
setValue("url", `${selectedType}://`);
return;
}
const hasProtocol = /^(http|https):\/\//i.test(url);
if (hasProtocol) {
const newUrl = url.replace(/^(http|https):\/\//i, `${selectedType}://`);
if (newUrl !== url) setValue("url", newUrl);
} else {
setValue("url", `${selectedType}://${url}`);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedType, setValue]);
useEffect(() => {
const input = urlInputRef.current;
if (input) {
const len = input.value.length;
input.setSelectionRange(len, len);
}
}, [selectedType]);
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
{mode === "create" && (
<ConfigBox
title={t("distributedUptimeCreateChecks")}
subtitle={t("distributedUptimeCreateChecksDescription")}
rightContent={
<Controller
name="type"
control={control}
render={({ field }) => (
<FormControl error={!!errors.type}>
<RadioGroup {...field} sx={{ gap: theme.spacing(6) }}>
<RadioWithDescription
value="https"
label="HTTPS"
description="Use HTTPS to monitor your website or API endpoint.
"
/>
<RadioWithDescription
value="http"
label={"HTTP"}
description={
"Use HTTP to monitor your website or API endpoint."
}
/>
<RadioWithDescription
value="ping"
label={t("pingMonitoring")}
description={t("pingMonitoringDescription")}
/>
</RadioGroup>
</FormControl>
)}
/>
}
/>
)}
<ConfigBox
title={t("settingsGeneralSettings")}
subtitle={t(`uptimeGeneralInstructions.${selectedType}`)}
rightContent={
<Stack gap={theme.spacing(8)}>
<Controller
disabled={mode === "configure"}
name="url"
control={control}
render={({ field }) => (
<TextInput
inputRef={urlInputRef}
{...field}
onFocus={(e) => {
const input = e.target;
setTimeout(() => {
input.setSelectionRange(
input.value.length,
input.value.length
);
}, 0);
}}
type="text"
fieldLabel={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("displayName")}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.incidentConfigTitle")}
subtitle={t("createMonitorPage.incidentConfigDescriptionV2")}
rightContent={
<Controller
name="n"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("createMonitorPage.incidentConfigStatusCheckNumber")}
fullWidth
error={!!errors.n}
helperText={errors.n ? errors.n.message : ""}
onChange={(e) => {
const target = e.target as HTMLInputElement;
field.onChange(target.valueAsNumber);
}}
/>
)}
/>
}
/>
<ConfigBox
title={t("notificationConfig.title")}
subtitle={t("notificationConfig.description")}
rightContent={
<Stack>
<Controller
name="notificationChannels"
control={control}
defaultValue={[]}
render={({ field }) => (
<AutoComplete
multiple
fieldLabel={`You have ${notificationOptions.length} available notification ${notificationOptions.length === 1 ? 'channel' : 'channels'}`}
options={notificationOptions}
getOptionLabel={(option) => option.name}
value={notificationOptions.filter((o: any) =>
(field.value || []).includes(o._id)
)}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
/>
)}
/>
<Stack gap={theme.spacing(2)} mt={theme.spacing(2)}>
{notificationChannels.map((notificationId) => {
const option = notificationOptions.find(
(o: any) => o._id === notificationId
);
if (!option) return null;
return (
<Stack
width={"100%"}
justifyContent={"space-between"}
direction="row"
key={notificationId}
>
<Typography>{option.name}</Typography>
<Trash2
size={20}
strokeWidth={1.5}
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
style={{ cursor: "pointer" }}
/>
</Stack>
);
})}
</Stack>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.intervalTitle")}
subtitle="How often to check the URL"
rightContent={
<Controller
name="interval"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createMonitorPage.intervalDescription")}
fullWidth
error={!!errors.interval}
helperText={errors.interval ? errors.interval.message : ""}
/>
)}
/>
}
/>
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
+104
View File
@@ -0,0 +1,104 @@
import {
MonitorBasePageWithStates,
UpStatusBox,
DownStatusBox,
PausedStatusBox,
InfoBox,
} from "@/components/design-elements";
import { HeaderCreate } from "@/components/monitors";
import Stack from "@mui/material/Stack";
import { Dialog } from "@/components/inputs";
import { MonitorTable } from "@/pages/uptime/MonitorTable";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithStats } from "@/types/monitor";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useState } from "react";
import { useDelete } from "@/hooks/UseApi";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const UptimeMonitors = () => {
const theme = useTheme();
const { t } = useTranslation();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const [selectedMonitor, setSelectedMonitor] = useState<IMonitor | null>(null);
const isDialogOpen = Boolean(selectedMonitor);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const { deleteFn } = useDelete();
const { response, loading, isValidating, error, refetch } = useGet<
ApiResponse<IMonitorWithStats>
>(
`/monitors?embedChecks=true&type=http&type=https&type=ping&page=${page}&rowsPerPage=${rowsPerPage}`,
{},
{
refreshInterval: GLOBAL_REFRESH,
keepPreviousData: true,
dedupingInterval: 0,
},
{
useTeamIdAsKey: true,
}
);
const monitors: IMonitor[] = response?.data?.monitors ?? ([] as IMonitor[]);
const count = response?.data?.count || 0;
const upCount = response?.data?.upCount || 0;
const downCount = response?.data?.downCount || 0;
const pausedCount = response?.data?.pausedCount || 0;
const handleConfirm = async () => {
await deleteFn(`/monitors/${selectedMonitor?._id}`);
setSelectedMonitor(null);
refetch();
};
const handleCancel = () => {
setSelectedMonitor(null);
};
return (
<MonitorBasePageWithStates
loading={isValidating}
error={error}
items={monitors}
page="uptime"
actionLink="/uptime/create"
>
<InfoBox
title="Website & API Uptime Monitoring"
description="Monitor your websites and APIs to ensure they're always accessible. Get instant alerts when your services go down and track uptime history over time."
/>
<HeaderCreate isLoading={loading} path="/uptime/create" />
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(8)}>
<UpStatusBox n={upCount} />
<DownStatusBox n={downCount} />
<PausedStatusBox n={pausedCount} />
</Stack>
<MonitorTable
monitors={monitors}
refetch={refetch}
setSelectedMonitor={setSelectedMonitor}
count={count}
page={page}
setPage={setPage}
rowsPerPage={rowsPerPage}
setRowsPerPage={setRowsPerPage}
/>
<Dialog
open={isDialogOpen}
title={t("deleteDialogTitle")}
content={t("deleteDialogDescription")}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</MonitorBasePageWithStates>
);
};
export default UptimeMonitors;