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

+63
View File
@@ -0,0 +1,63 @@
import { BaseBox } from "../design-elements";
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
type BaseChartProps = React.PropsWithChildren<{
icon: React.ReactNode;
title: string;
width?: number | string;
maxWidth?: number | string;
}>;
export const BaseChart: React.FC<BaseChartProps> = ({
children,
icon,
title,
width = "100%",
maxWidth = "100%",
}) => {
const theme = useTheme();
return (
<BaseBox
sx={{
padding: theme.spacing(8),
display: "flex",
flex: 1,
width: width,
maxWidth: maxWidth,
}}
>
<Stack gap={theme.spacing(8)} flex={1}>
<Stack direction="row" alignItems={"center"} gap={theme.spacing(4)}>
{icon && (
<BaseBox
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
width: 34,
height: 34,
backgroundColor: theme.palette.primary.veryLowContrast,
"& svg": {
width: 20,
height: 20,
"& path": {
stroke: theme.palette.primary.contrastTextTertiary,
},
},
}}
>
{icon}
</BaseBox>
)}
<Typography variant="h2">{title}</Typography>
</Stack>
<Box flex={1}>{children}</Box>
</Stack>
</BaseBox>
);
};
@@ -0,0 +1,74 @@
import { BaseChart } from "@/components/monitors/Chart";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { Gauge } from "lucide-react";
import { Cell, RadialBarChart, RadialBar, ResponsiveContainer } from "recharts";
import { getResponseTimeColor } from "@/utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
export const ChartAvgResponse = ({
avg,
max,
}: {
avg: number;
max: number;
}) => {
const theme = useTheme();
const chartData = [
{ name: "max", value: max - avg, color: "transparent" },
{ name: "avg", value: avg, color: "red" },
];
const palette = getResponseTimeColor(avg);
const msg: Record<string, string> = {
success: "Excellent",
warning: "Average",
danger: "Poor",
};
return (
<BaseChart icon={<Gauge size={20} strokeWidth={1.5} />} title={"Average response time"}>
<Stack height="100%" position={"relative"} justifyContent={"flex-end"}>
<ResponsiveContainer width="100%" height={155}>
<RadialBarChart
cy="100%"
data={chartData}
startAngle={180}
endAngle={0}
innerRadius={"120%"}
outerRadius={"200%"}
>
<RadialBar
dataKey="value"
background={{ fill: theme.palette[palette].lowContrast }}
>
<Cell visibility={"hidden"} />
<Cell fill={theme.palette[palette].main} />
</RadialBar>
</RadialBarChart>
</ResponsiveContainer>
<Stack direction={"row"} justifyContent={"space-between"}>
<Typography variant="body2">Low</Typography>
<Typography variant="body2">High</Typography>
</Stack>
<Stack
position="absolute"
top={"50%"}
right={"50%"}
sx={{
transform: "translate(50%, 0%)",
}}
>
<Typography variant="h6" textAlign={"center"}>
{msg[palette]}
</Typography>
<Typography
variant="h6"
textAlign={"center"}
>{`${avg?.toFixed()}ms`}</Typography>
</Stack>
</Stack>
</BaseChart>
);
};
@@ -0,0 +1,92 @@
import { BaseChart } from "@/components/monitors/Chart";
import { FileText } from "lucide-react";
import { Pie, PieChart, ResponsiveContainer, Label } from "recharts";
import Typography from "@mui/material/Typography";
import { getPageSpeedPalette } from "@/utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
import { alpha } from "@mui/material/styles";
const CenterLabel = ({ viewBox, value }: any) => {
const { cx, cy } = viewBox;
return (
<foreignObject x={cx - 25} y={cy - 10} width={50} height={50}>
<Typography variant="h1" align="center">
{value}
</Typography>
</foreignObject>
);
};
export const ChartPageSpeedReport = ({ latestCheck }: { latestCheck: any }) => {
const theme = useTheme();
const metrics = [
{ key: "fcp", color: alpha("#1DE9B6", 0.6), weight: 0.1 },
{ key: "si", color: alpha("#7C4DFF", 0.6), weight: 0.1 },
{ key: "lcp", color: alpha("#FFB200", 0.6), weight: 0.25 },
{ key: "tbt", color: alpha("#00AFFE", 0.6), weight: 0.3 },
{ key: "cls", color: alpha("#FF4181", 0.6), weight: 0.25 },
];
const scores = metrics.flatMap(({ key, color, weight }) => {
const val = Math.floor((latestCheck?.[key] ?? 0) * 100);
const inverse = 100 - val;
return [
{
name: `${key.toUpperCase()} Inverse`,
value: inverse * weight,
fill: "transparent",
stroke: color,
weight,
},
{
name: key.toUpperCase(),
value: val * weight,
fill: color,
stroke: color,
weight,
},
];
});
const totalScore =
(latestCheck?.fcp || 0) * 0.1 +
(latestCheck?.si || 0) * 0.1 +
(latestCheck?.lcp || 0) * 0.25 +
(latestCheck?.tbt || 0) * 0.3 +
(latestCheck?.cls || 0) * 0.25;
const pageSpeedPalette = getPageSpeedPalette(Math.floor(totalScore * 100));
const score = [
{
value: 100,
fill: alpha(
theme.palette[pageSpeedPalette].lowContrast || "#ffffff",
0.6
),
stroke: "none",
},
];
return (
<BaseChart icon={<FileText size={20} strokeWidth={1.5} />} title="Average PageSpeed score">
<ResponsiveContainer width="100%" height={250}>
<PieChart>
<Pie data={score} dataKey="value" cx="50%" cy="50%" outerRadius="65%">
<Label
position={"center"}
content={<CenterLabel value={Math.floor(totalScore * 100)} />}
/>
</Pie>
<Pie
data={scores}
innerRadius="70%"
outerRadius="80%"
label={({ name, value }) => `${name}: ${Math.round(value)}`}
dataKey="value"
/>
</PieChart>
</ResponsiveContainer>
</BaseChart>
);
};
@@ -0,0 +1,87 @@
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import { BarChart3 } from "lucide-react";
import { BaseChart } from "@/components/monitors/Chart";
import Typography from "@mui/material/Typography";
import { getPageSpeedPalette } from "@/utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
const MetricBox = ({
label,
value,
weight,
}: {
label: string;
value: number;
weight: number;
}) => {
const theme = useTheme();
const palette = getPageSpeedPalette(value);
return (
<Stack
direction={"row"}
sx={{
border: 1,
borderStyle: "solid",
borderColor: theme.palette.primary.lowContrast,
borderRadius: theme.shape.borderRadius,
}}
>
<Stack flex={1} p={theme.spacing(4)}>
<Typography textTransform={"uppercase"}>{label}</Typography>
<Stack direction="row" justifyContent={"space-between"}>
<Typography>{`${value}%`}</Typography>
<Typography>{`Weight: ${weight}%`}</Typography>
</Stack>
</Stack>
<Box
width={4}
bgcolor={theme.palette[palette].lowContrast}
sx={{
borderTopRightRadius: theme.shape.borderRadius,
borderBottomRightRadius: theme.shape.borderRadius,
}}
/>
</Stack>
);
};
export const ChartPageSpeedReportLegend = ({
latestCheck,
}: {
latestCheck: any;
}) => {
const theme = useTheme();
return (
<BaseChart icon={<BarChart3 size={20} strokeWidth={1.5} />} title="PageSpeed report">
<Stack gap={theme.spacing(4)}>
<MetricBox
label="Speed index (SI)"
value={Math.floor(latestCheck?.si * 100 || 0 * 100)}
weight={10}
/>
<MetricBox
label="First contentful paint (FCP)"
value={Math.floor(latestCheck?.fcp * 100 || 0 * 100)}
weight={10}
/>
<MetricBox
label="Cumulative layout shift (CLS)"
value={Math.floor(latestCheck?.cls * 100 || 0 * 100)}
weight={25}
/>
<MetricBox
label="Total blocking time (TBT)"
value={Math.floor(latestCheck?.tbt * 100 || 0 * 100)}
weight={30}
/>
<MetricBox
label="Largest contentful paint (LCP)"
value={Math.floor(latestCheck?.lcp * 100 || 0 * 100)}
weight={25}
/>
</Stack>
</BaseChart>
);
};
@@ -0,0 +1,148 @@
import { BaseChart } from "@/components/monitors/Chart";
import { BaseBox } from "@/components/design-elements";
import { Clock } from "lucide-react";
import { normalizeResponseTimes } from "@/utils/DataUtils";
import {
AreaChart,
Area,
XAxis,
Tooltip,
CartesianGrid,
ResponsiveContainer,
Text,
} from "recharts";
import Typography from "@mui/material/Typography";
import {
formatDateWithTz,
tickDateFormatLookup,
tooltipDateFormatLookup,
} from "@/utils/TimeUtils";
import { useTheme } from "@mui/material/styles";
import type { GroupedCheck } from "@/types/check";
import { useAppSelector } from "@/hooks/AppHooks";
type XTickProps = {
x: number;
y: number;
payload: { value: any };
range: string;
};
export const XTick: React.FC<XTickProps> = ({ x, y, payload, range }) => {
const format = tickDateFormatLookup(range);
const theme = useTheme();
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
return (
<Text
x={x}
y={y + 10}
textAnchor="middle"
fill={theme.palette.primary.contrastTextTertiary}
fontSize={11}
fontWeight={400}
>
{formatDateWithTz(payload?.value, format, uiTimezone)}
</Text>
);
};
type ResponseTimeToolTipProps = {
active?: boolean | undefined;
payload?: any[];
label?: string | number;
range: string;
theme: any;
uiTimezone: string;
};
const ResponseTimeToolTip: React.FC<ResponseTimeToolTipProps> = ({
active,
payload,
label,
range,
theme,
uiTimezone,
}) => {
if (!label) return null;
if (!payload) return null;
if (!active) return null;
const format = tooltipDateFormatLookup(range);
const responseTime = Math.floor(payload?.[0]?.payload?.avgResponseTime || 0);
return (
<BaseBox sx={{ py: theme.spacing(2), px: theme.spacing(4) }}>
<Typography>
{formatDateWithTz(String(label), format, uiTimezone)}
</Typography>
<Typography>Response time: {responseTime} ms</Typography>
</BaseBox>
);
};
export const ChartResponseTime = ({
checks,
range,
}: {
checks: GroupedCheck[];
range: string;
}) => {
const theme = useTheme();
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const normalized = normalizeResponseTimes<GroupedCheck, "avgResponseTime">(
checks,
"avgResponseTime"
);
return (
<BaseChart icon={<Clock size={20} strokeWidth={1.5} />} title="Response times">
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={normalized?.slice().reverse()}>
<CartesianGrid
stroke={theme.palette.primary.lowContrast}
strokeWidth={1}
strokeOpacity={1}
fill="transparent"
vertical={false}
/>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop
offset="0%"
stopColor={theme.palette.accent.main}
stopOpacity={0.8}
/>
<stop
offset="100%"
stopColor={theme.palette.accent.light}
stopOpacity={0}
/>
</linearGradient>
</defs>
<XAxis
axisLine={false}
tickLine={false}
dataKey="_id"
tick={(props) => <XTick {...props} range={range} />}
/>
<Tooltip
content={(props) => (
<ResponseTimeToolTip
{...props}
range={range}
theme={theme}
uiTimezone={uiTimezone}
/>
)}
/>
<Area
type="monotone"
dataKey="normalResponseTime"
stroke={theme.palette.accent.main}
fill="url(#colorUv)"
/>
</AreaChart>
</ResponsiveContainer>
</BaseChart>
);
};
@@ -0,0 +1,93 @@
import Stack from "@mui/material/Stack";
import { MonitorStatus } from "@/components/monitors/MonitorStatus";
import { ButtonGroup, Button } from "@/components/inputs";
import { Settings, Pause, Play, Mail, Bug } from "lucide-react";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router";
import type { IMonitor } from "@/types/monitor";
import { usePost } from "@/hooks/UseApi";
export const HeaderControls = ({
monitor,
patch,
isPatching,
refetch,
path,
}: {
monitor: IMonitor;
patch: Function;
isPatching: boolean;
refetch: Function;
path: string;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const navigate = useNavigate();
const { post, loading: isPosting } = usePost<any, any>();
const hasNotificationChannels = monitor?.notificationChannels.length > 0;
return (
<Stack
direction={isSmall ? "column" : "row"}
spacing={isSmall ? theme.spacing(4) : 0}
justifyContent={"space-between"}
>
<MonitorStatus monitor={monitor} />
<Stack direction={"row"} spacing={theme.spacing(2)}>
<ButtonGroup
orientation={isSmall ? "vertical" : "horizontal"}
fullWidth={isSmall}
variant="contained"
color="secondary"
>
{hasNotificationChannels && (
<Button
loading={isPosting || isPatching}
startIcon={<Mail size={20} strokeWidth={1.5} />}
onClick={async () => {
await post(`/monitors/${monitor._id}/notifications/test`, {});
}}
>
{t("sendTestNotifications")}
</Button>
)}
<Button
startIcon={<Bug size={20} strokeWidth={1.5} />}
onClick={() => {
navigate(`/incidents/${monitor._id}`);
}}
>
{t("menu.incidents")}
</Button>
<Button
loading={isPatching || isPosting}
onClick={async () => {
await patch(`/monitors/${monitor._id}/active`);
refetch();
}}
startIcon={
monitor?.isActive ? (
<Pause size={20} strokeWidth={1.5} />
) : (
<Play size={20} strokeWidth={1.5} />
)
}
>
{monitor?.isActive ? t("pause") : t("resume")}
</Button>
<Button
startIcon={<Settings size={20} strokeWidth={1.5} />}
onClick={() => {
navigate(`${path}/${monitor._id}/configure`);
}}
>
{t("configure")}
</Button>
</ButtonGroup>
</Stack>
</Stack>
);
};
@@ -0,0 +1,35 @@
import Stack from "@mui/material/Stack";
import { Button } from "@/components/inputs";
import { useTheme } from "@mui/material/styles";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router";
export const HeaderCreate = ({
label,
isLoading,
path,
}: {
label?: string;
isLoading: boolean;
path: string;
}) => {
const theme = useTheme();
const { t } = useTranslation();
const navigate = useNavigate();
return (
<Stack
direction="row"
justifyContent="end"
alignItems="center"
gap={theme.spacing(6)}
>
<Button
loading={isLoading}
variant="contained"
color="accent"
onClick={() => navigate(path)}
>
{label || t("createNew")}
</Button>
</Stack>
);
};
@@ -0,0 +1,179 @@
import { BaseChart } from "@/components/monitors/Chart";
import {
AreaChart,
Area,
XAxis,
YAxis,
CartesianGrid,
ResponsiveContainer,
} from "recharts";
import { Fragment, useId } from "react";
import { XTick } from "./ChartResponseTime";
import { useTheme } from "@mui/material/styles";
import type { IInfraCheck } from "@/types/check";
const AREA_COLORS = [
// Blues
"#3182bd", // Deep blue
"#6baed6", // Medium blue
"#9ecae1", // Light blue
// Greens
"#74c476", // Soft green
"#a1d99b", // Light green
"#c7e9c0", // Pale green
// Oranges
"#fdae6b", // Warm orange
"#fdd0a2", // Light orange
"#feedde", // Pale orange
// Purples
"#9467bd", // Lavender
"#a55194", // Deep magenta
"#c994c7", // Soft magenta
// Reds
"#ff9896", // Soft red
"#de2d26", // Deep red
"#fc9272", // Medium red
// Cyans/Teals
"#17becf", // Cyan
"#7fcdbb", // Teal
"#a1dab4", // Light teal
// Yellows
"#fec44f", // Mustard
"#fee391", // Light yellow
"#ffffd4", // Pale yellow
// Additional colors
"#e377c2", // Soft pink
"#bcbd22", // Olive
"#2ca02c", // Vibrant green
];
const createGradient = ({
id,
startColor,
endColor,
startOpacity = 0.8,
endOpacity = 0,
direction = "vertical",
}: {
id: string;
startColor: string;
endColor: string;
startOpacity?: number;
endOpacity?: number;
direction?: "vertical" | "horizontal";
}) => (
<defs>
<linearGradient
id={id}
x1={direction === "vertical" ? "0" : "0"}
y1={direction === "vertical" ? "0" : "0"}
x2={direction === "vertical" ? "0" : "1"}
y2={direction === "vertical" ? "1" : "0"}
>
<stop offset="0%" stopColor={startColor} stopOpacity={startOpacity} />
<stop offset="100%" stopColor={endColor} stopOpacity={endOpacity} />
</linearGradient>
</defs>
);
export const HistogramInfrastructure = ({
range,
title,
idx,
checks,
xKey,
yDomain,
dataKeys,
gradient = false,
gradientDirection = "vertical",
gradientStartColor,
gradientEndColor,
strokeColor,
fillColor,
}: {
range: string;
title: string;
idx: number | null;
checks: IInfraCheck[];
xKey: string;
yDomain?: number[];
dataKeys: string[];
gradient?: boolean;
gradientDirection?: "vertical" | "horizontal";
gradientStartColor?: string;
gradientEndColor?: string;
strokeColor: string;
fillColor?: string;
}) => {
const theme = useTheme();
const uniqueId = useId();
let avgTemps: { _id: string; avg_temp: number | null }[] = [];
let tempYDomain: number[] = [];
if (title === "temp") {
avgTemps = checks.map((check) => {
const temps = check.cpu.temperature || [];
if (temps.length === 0) return { ...check, avg_temp: null };
const totalTemp = temps.reduce((sum, temp) => sum + (temp || 0), 0);
const avgTemp = totalTemp / temps.length;
return { _id: check._id, avg_temp: avgTemp };
});
const maxTemp: number = avgTemps.reduce((max, item) => {
return item.avg_temp && item.avg_temp > max ? item.avg_temp : max;
}, 0);
tempYDomain = [0, Math.ceil((maxTemp * 1.3) / 10) * 10];
}
return (
<BaseChart icon={null} title={idx !== null ? title + ` ${idx}` : title}>
<ResponsiveContainer width="100%" height={200}>
<AreaChart data={title === "temp" ? avgTemps : checks}>
<XAxis
dataKey={xKey}
tick={(props) => <XTick {...props} range={range} />}
/>
<YAxis domain={title === "temp" ? tempYDomain : yDomain} />
<CartesianGrid
stroke={theme.palette.primary.lowContrast}
strokeWidth={1}
strokeOpacity={1}
fill="transparent"
vertical={false}
/>
{dataKeys?.map((dataKey, index) => {
const gradientId = `gradient-${uniqueId}-${index}`;
return (
<Fragment key={dataKey}>
{gradient === true &&
createGradient({
id: gradientId,
startColor: gradientStartColor || AREA_COLORS[index],
endColor: gradientEndColor || "transparent",
direction: gradientDirection,
})}
<Area
key={dataKey}
type="monotone"
dataKey={dataKey}
stroke={strokeColor || AREA_COLORS[index]}
fill={gradient === true ? `url(#${gradientId})` : fillColor}
/>
</Fragment>
);
})}
</AreaChart>
</ResponsiveContainer>
</BaseChart>
);
};
@@ -0,0 +1,103 @@
import Stack from "@mui/material/Stack";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
} from "recharts";
import { HistogramPageSpeedTooltip } from "@/components/monitors/HistogramPageSpeedTooltip";
import { useTheme } from "@mui/material/styles";
import type { ICheck } from "@/types/check";
import type { MonitorStatus } from "@/types/monitor";
import { getStatusColor } from "@/utils/MonitorUtils";
const processData = (checks: ICheck[]) => {
if (checks.length === 0) return [];
const formattedData: { score: number; date: string }[] = [];
const calculateScore = (entry: ICheck) => {
const accessibility = entry?.lighthouse?.accessibility || 0;
const bestPractices = entry?.lighthouse?.bestPractices || 0;
const performance = entry?.lighthouse?.performance || 0;
const seo = entry?.lighthouse?.seo || 0;
return Math.floor(
((accessibility + bestPractices + performance + seo) / 4) * 100
);
};
checks.forEach((entry) => {
const score = calculateScore(entry);
const date = entry.createdAt;
formattedData.push({ score, date });
});
return formattedData;
};
export const HistogramPageSpeed = ({
checks,
status,
}: {
checks: ICheck[];
status: MonitorStatus;
}) => {
const theme = useTheme();
const scores = processData(checks);
const color = getStatusColor(status, theme);
return (
<Stack
direction="row"
flexWrap="nowrap"
gap={theme.spacing(1.5)}
height="100px"
width="400px"
onClick={(event) => event.stopPropagation()}
overflow={"hidden"}
sx={{
cursor: "default",
position: "relative",
}}
>
<ResponsiveContainer width="100%" height={"100%"}>
<AreaChart
data={scores}
margin={{ top: 10, bottom: -5 }}
style={{ cursor: "pointer" }}
>
<CartesianGrid
stroke={theme.palette.primary.lowContrast}
strokeWidth={1}
strokeOpacity={1}
fill="transparent"
vertical={false}
/>
<Tooltip
cursor={{ stroke: theme.palette.primary.lowContrast }}
content={<HistogramPageSpeedTooltip />}
/>
<defs>
<linearGradient
id={`pagespeed-chart-${status}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop offset="0%" stopColor={color} stopOpacity={0.8} />
<stop offset="100%" stopColor={color} stopOpacity={0} />
</linearGradient>
</defs>
<Area
type="monotone"
dataKey="score"
stroke={color}
fill={`url(#pagespeed-chart-${status})`}
/>
</AreaChart>
</ResponsiveContainer>
</Stack>
);
};
@@ -0,0 +1,104 @@
import { BaseChart } from "@/components/monitors/Chart";
import { TrendingUp } from "lucide-react";
import {
AreaChart,
Area,
Tooltip,
CartesianGrid,
ResponsiveContainer,
} from "recharts";
import { HistogramPageSpeedScoresTooltip } from "./HistogramPageSpeedScoresTooltip";
import { useTheme } from "@mui/material/styles";
import type { GroupedCheck } from "@/types/check";
import type { Palette } from "@mui/material/styles";
type PaletteColorKey = Extract<
keyof Palette,
"primary" | "secondary" | "success" | "warning" | "accent"
>;
export interface ConfigItem {
id: string;
text: string;
palette: PaletteColorKey;
}
const config: Record<string, ConfigItem> = {
seo: {
id: "seo",
text: "SEO",
palette: "secondary",
},
performance: {
id: "performance",
text: "performance",
palette: "success",
},
bestPractices: {
id: "bestPractices",
text: "best practices",
palette: "warning",
},
accessibility: {
id: "accessibility",
text: "accessibility",
palette: "accent",
},
};
export const HistogramPageSpeedScores = ({
checks,
}: {
checks: GroupedCheck[];
}) => {
const theme = useTheme();
return (
<BaseChart icon={<TrendingUp size={20} strokeWidth={1.5} />} title="Score history">
<ResponsiveContainer width="100%" minWidth={25} height={215}>
<AreaChart data={checks}>
<CartesianGrid
stroke={theme.palette.primary.lowContrast}
strokeWidth={1}
strokeOpacity={1}
fill="transparent"
vertical={false}
/>
<Tooltip
cursor={{ stroke: theme.palette.primary.lowContrast }}
content={<HistogramPageSpeedScoresTooltip config={config} />}
/>
<defs>
{Object.values(config).map(({ id, palette }) => {
const startColor = theme.palette[palette].main;
const endColor = theme.palette[palette].lowContrast;
return (
<linearGradient id={id} x1="0" y1="0" x2="0" y2="1" key={id}>
<stop offset="0%" stopColor={startColor} stopOpacity={0.8} />
<stop offset="100%" stopColor={endColor} stopOpacity={0} />
</linearGradient>
);
})}
</defs>
{Object.keys(config).map((key) => {
const { palette } = config[key];
const strokeColor = theme.palette[palette].main;
const bgColor = theme.palette.primary.main;
return (
<Area
connectNulls
key={key}
dataKey={key}
stackId={1}
stroke={strokeColor}
fill={`url(#${config[key].id})`}
activeDot={{ stroke: bgColor, fill: strokeColor, r: 4.5 }}
/>
);
})}
</AreaChart>
</ResponsiveContainer>
</BaseChart>
);
};
@@ -0,0 +1,76 @@
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";
import { useAppSelector } from "@/hooks/AppHooks";
import { formatDateWithTz } from "@/utils/TimeUtils";
import type { ConfigItem } from "@/components/monitors/HistogramPageSpeedScores";
import type { TooltipProps } from "recharts";
interface HistogramPageSpeedScoresTooltipProps
extends Partial<TooltipProps<number, string>> {
config: Record<string, ConfigItem>;
}
export const HistogramPageSpeedScoresTooltip = ({
active,
payload,
label,
config,
}: HistogramPageSpeedScoresTooltipProps) => {
const theme = useTheme();
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
if (active && payload && payload.length) {
return (
<Box
sx={{
backgroundColor: theme.palette.primary.main,
border: 1,
borderColor: theme.palette.primary.lowContrast,
borderRadius: theme.shape.borderRadius,
py: theme.spacing(2),
px: theme.spacing(4),
}}
>
<Typography
sx={{
color: theme.palette.primary.contrastTextTertiary,
fontSize: 12,
fontWeight: 500,
}}
>
{formatDateWithTz(label, "ddd, MMMM D, YYYY, h:mm A", uiTimezone)}
</Typography>
{Object.keys(config)
.reverse()
.map((key) => {
const { palette } = config[key];
const dotColor = theme.palette[palette].main;
return (
<Stack
key={`${key}-tooltip`}
direction="row"
alignItems="center"
gap={theme.spacing(3)}
mt={theme.spacing(1)}
>
<Box
width={theme.spacing(4)}
height={theme.spacing(4)}
sx={{ borderRadius: "50%", backgroundColor: dotColor }}
/>
<Typography textTransform="capitalize" sx={{ opacity: 0.8 }}>
{config[key].text}
</Typography>
<Typography>
{Math.floor(payload[0].payload[key] * 100)}
</Typography>
</Stack>
);
})}
</Box>
);
}
return null;
};
@@ -0,0 +1,39 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
import type { TooltipProps } from "recharts";
import { useTheme } from "@mui/material/styles";
export const HistogramPageSpeedTooltip = ({
payload,
}: TooltipProps<string | number, string>) => {
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const theme = useTheme();
return (
<Stack
alignItems={"flex-start"}
top={0}
left={0}
zIndex={10}
sx={{
backgroundColor: theme.palette.secondary.main,
border: 1,
borderColor: theme.palette.primary.lowContrast,
borderRadius: theme.shape.borderRadius,
p: theme.spacing(4),
}}
>
<Typography color={theme.palette.primary.contrastText}>
{formatDateWithTz(
payload?.[0]?.payload?.date ?? 0,
"MMMM D, YYYY, HH:mm A",
uiTimezone
)}
</Typography>
<Typography color={theme.palette.primary.contrastText}>
Score: {payload?.[0]?.payload?.score}
</Typography>
</Stack>
);
};
@@ -0,0 +1,87 @@
import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import { useTheme } from "@mui/material/styles";
import type { ICheck } from "@/types/check";
import { HistogramResponseTimeTooltip } from "@/components/monitors/HistogramResponseTimeTooltip";
import { normalizeResponseTimes } from "@/utils/DataUtils";
export const HistogramResponseTime = ({ checks }: { checks: ICheck[] }) => {
const theme = useTheme();
const normalChecks = normalizeResponseTimes(checks, "responseTime");
const BAR_WIDTH = { xs: theme.spacing(2.5), md: theme.spacing(4.5) };
let data = Array<any>();
if (!normalChecks || normalChecks.length === 0) {
return null;
}
if (normalChecks.length !== 25) {
const placeholders = Array(25 - normalChecks.length).fill("placeholder");
data = [...normalChecks, ...placeholders];
} else {
data = normalChecks;
}
return (
<Stack
direction="row"
flexWrap="nowrap"
gap={theme.spacing(1.5)}
height="50px"
width="fit-content"
onClick={(event) => event.stopPropagation()}
sx={{
cursor: "default",
}}
>
{data.map((check, index) => {
if (check === "placeholder") {
return (
<Box
key={`${check}-${index}`}
position="relative"
width={BAR_WIDTH}
height="100%"
bgcolor={theme.palette.primary.veryLowContrast}
sx={{
borderRadius: theme.spacing(1.5),
}}
/>
);
} else {
return (
<HistogramResponseTimeTooltip
key={`${check}-${index}`}
check={check}
>
<Box
position="relative"
height="100%"
bgcolor={theme.palette.primary.veryLowContrast}
width={BAR_WIDTH}
sx={{
borderRadius: theme.spacing(1.5),
}}
>
<Box
position="absolute"
bottom={0}
width="100%"
height={`${check.normalResponseTime}%`}
bgcolor={
check.status === "up"
? theme.palette.success.lowContrast
: theme.palette.error.lowContrast
}
sx={{
borderRadius: theme.spacing(1.5),
transition: "height 600ms cubic-bezier(0.4, 0, 0.2, 1)",
}}
/>
</Box>
</HistogramResponseTimeTooltip>
);
}
})}
</Stack>
);
};
@@ -0,0 +1,56 @@
import Stack from "@mui/material/Stack";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
import type { LatestCheck } from "@/types/check";
import { useTheme } from "@mui/material/styles";
export const HistogramResponseTimeTooltip: React.FC<{
children: React.ReactElement;
check: LatestCheck;
}> = ({ children, check }) => {
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const theme = useTheme();
if (check.status === "placeholder") {
return children;
}
return (
<Tooltip
slotProps={{
tooltip: {
sx: {
backgroundColor: "transparent",
color: "inherit",
boxShadow: "none",
},
},
}}
title={
<Stack
sx={{
backgroundColor: theme.palette.secondary.main,
border: 1,
borderColor: theme.palette.primary.lowContrast,
borderRadius: theme.shape.borderRadius,
p: theme.spacing(4),
}}
>
<Typography>
{formatDateWithTz(
check?.checkedAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
)}
</Typography>
{check?.responseTime && (
<Typography>Response Time: {check.responseTime} ms</Typography>
)}
</Stack>
}
>
{children}
</Tooltip>
);
};
@@ -0,0 +1,156 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { BaseChart } from "@/components/monitors/Chart";
import { ResponsiveContainer, BarChart, XAxis, Bar, Cell } from "recharts";
import { TrendingUp, AlertTriangle } from "lucide-react";
import type { GroupedCheck } from "@/types/check";
import type { MonitorStatus } from "@/types/monitor";
import { normalizeResponseTimes } from "@/utils/DataUtils";
import { useState } from "react";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
import { useTheme } from "@mui/material/styles";
import { getResponseTimeColor } from "@/utils/MonitorUtils";
const XLabel = ({
p1,
p2,
range,
}: {
p1: GroupedCheck;
p2: GroupedCheck;
range: string;
}) => {
const theme = useTheme();
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const dateFormat = range === "day" ? "MMM D, h:mm A" : "MMM D";
return (
<>
<text
x={0}
y="100%"
dy={-3}
textAnchor="start"
fontSize={11}
fill={theme.palette.primary.contrastTextTertiary}
>
{formatDateWithTz(p1._id, dateFormat, uiTimezone)}
</text>
<text
x="100%"
y="100%"
dy={-3}
textAnchor="end"
fontSize={11}
fill={theme.palette.primary.contrastTextTertiary}
>
{formatDateWithTz(p2._id, dateFormat, uiTimezone)}
</text>
</>
);
};
export const HistogramStatus = ({
checks,
status,
range,
title,
}: {
checks: GroupedCheck[];
status: MonitorStatus;
range: string;
title: string;
}) => {
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const icon = status === "up" ? <TrendingUp size={20} strokeWidth={1.5} /> : <AlertTriangle size={20} strokeWidth={1.5} />;
const theme = useTheme();
const [idx, setIdx] = useState<number | null>(null);
const dateFormat = range === "1d" || range === "2h" ? "MMM D, h A" : "MMM D";
const normalChecks = normalizeResponseTimes(checks, "avgResponseTime");
if (normalChecks.length === 0) {
return (
<BaseChart icon={icon} title={title}>
<Stack height={"100%"} alignItems={"center"} justifyContent={"center"}>
<Typography variant="h2">
{status === "up" ? "No checks yet" : "Great, no downtime yet!"}
</Typography>
</Stack>
</BaseChart>
);
}
const totalChecks = normalChecks.reduce((count, check) => {
return count + check.count;
}, 0);
return (
<BaseChart icon={icon} title={title}>
<Stack gap={theme.spacing(8)}>
<Stack
position="relative"
direction="row"
justifyContent="space-between"
>
<Stack>
<Typography>Total checks</Typography>
{idx ? (
<Stack>
<Typography variant="h2">
{normalChecks?.[idx]?.count}
</Typography>
<Typography position={"absolute"} top={"100%"}>
{formatDateWithTz(
normalChecks?.[idx]?._id,
dateFormat,
uiTimezone
)}
</Typography>
</Stack>
) : (
<Typography variant="h2">{totalChecks}</Typography>
)}
</Stack>
</Stack>
<ResponsiveContainer width="100%" height={155}>
<BarChart data={normalChecks}>
<XAxis
stroke={theme.palette.primary.lowContrast}
height={15}
tick={false}
label={
<XLabel
p1={normalChecks[0]}
p2={normalChecks[normalChecks.length - 1]}
range={range}
/>
}
/>
<Bar
dataKey="normalResponseTime"
maxBarSize={7}
background={{ fill: "transparent" }}
>
{normalChecks?.map((groupedCheck, idx) => {
const fillColor = getResponseTimeColor(
groupedCheck.normalResponseTime
);
return (
<Cell
onMouseEnter={() => setIdx(idx)}
onMouseLeave={() => setIdx(null)}
key={groupedCheck._id}
fill={theme.palette[fillColor].main}
/>
);
})}
</Bar>
</BarChart>
</ResponsiveContainer>
</Stack>
</BaseChart>
);
};
@@ -0,0 +1,60 @@
import type { IMonitor } from "@/types/monitor";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { PulseDot, Dot } from "@/components/design-elements";
import { getStatusColor, formatUrl } from "@/utils/MonitorUtils";
import { useTheme } from "@mui/material/styles";
import prettyMilliseconds from "pretty-ms";
import { typographyLevels } from "@/theme/palette";
import useMediaQuery from "@mui/material/useMediaQuery";
export const MonitorStatus = ({ monitor }: { monitor: IMonitor }) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
if (!monitor) {
return null;
}
return (
<Stack>
<Typography
fontSize={typographyLevels.xl}
fontWeight={500}
color={theme.palette.primary.contrastText}
overflow={"hidden"}
textOverflow={"ellipsis"}
whiteSpace={"nowrap"}
maxWidth={
isSmall ? "100%" : "calc((100vw - var(--env-var-width-2)) / 2)"
}
>
{monitor.name}
</Typography>
<Stack direction="row" alignItems={"center"} gap={theme.spacing(4)}>
<PulseDot color={getStatusColor(monitor.status, theme)} />
<Typography
color={theme.palette.primary.contrastTextSecondary}
fontSize={typographyLevels.l}
fontWeight={"bolder"}
fontFamily={"monospace"}
overflow={"hidden"}
textOverflow={"ellipsis"}
whiteSpace={"nowrap"}
maxWidth={
isSmall ? "100%" : "calc((100vw - var(--env-var-width-2)) / 2)"
}
>
{formatUrl(monitor?.url)}
</Typography>
{!isSmall && (
<>
<Dot />
<Typography>
Checking every{" "}
{prettyMilliseconds(monitor?.interval, { verbose: true })}
</Typography>
</>
)}
</Stack>
</Stack>
);
};
+9
View File
@@ -0,0 +1,9 @@
export { HeaderCreate } from "./HeaderCreate";
export { HistogramStatus } from "./HistogramStatus";
export { ChartAvgResponse } from "./ChartAvgResponse";
export { HeaderRange } from "../common/HeaderRange";
export { HeaderControls } from "./HeaderControls";
export { ChartResponseTime } from "./ChartResponseTime";
export { HistogramResponseTime } from "./HistogramResponseTime";
export { HistogramPageSpeed } from "./HistogramPageSpeed";
export { HistogramInfrastructure } from "./HistogramInfrastructure";