Fixed the tool tip.

This commit is contained in:
owiaseimdad committed 2025-08-03 01:26:13 +05:30
1 parent 7b963ca877
commit 10c5463892
4 files changed
+214 -152

No files matched your search

@@ -112,6 +112,7 @@ export const InfrastructureTooltip = ({
yLabel, yLabel,
dotColor, dotColor,
dateRange, dateRange,
formatter = getFormattedPercentage,
}) => { }) => {
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
const theme = useTheme(); const theme = useTheme();
@@ -166,8 +167,8 @@ export const InfrastructureTooltip = ({
sx={{ opacity: 0.8 }} sx={{ opacity: 0.8 }}
> >
{yIdx >= 0 {yIdx >= 0
? `${yLabel} ${getFormattedPercentage(payload[0].payload[hardwareType][yIdx][metric])}` ? `${yLabel} ${formatter(payload[0].payload[hardwareType][yIdx][metric])}`
: `${yLabel} ${getFormattedPercentage(payload[0].payload[yKey])}`} : `${yLabel} ${formatter(payload[0].payload[yKey])}`}
</Typography> </Typography>
</Stack> </Stack>
</Box> </Box>
@@ -2,7 +2,7 @@
import { Grid, Card, CardContent, Typography } from "@mui/material"; import { Grid, Card, CardContent, Typography } from "@mui/material";
import { useTheme } from "@mui/material/styles"; import { useTheme } from "@mui/material/styles";
import AreaChart from "../../../../../Components/Charts/AreaChart"; import AreaChart from "../../../../../Components/Charts/AreaChart";
import { TzTick } from '../../../../../Components/Charts/Utils/chartUtils'; import { TzTick, InfrastructureTooltip } from '../../../../../Components/Charts/Utils/chartUtils';
const BytesTick = ({ x, y, payload }) => { const BytesTick = ({ x, y, payload }) => {
const value = payload.value; const value = payload.value;
@@ -16,37 +16,89 @@ const BytesTick = ({ x, y, payload }) => {
return <text x={x} y={y} textAnchor="end" fill="#888">{label}</text>; return <text x={x} y={y} textAnchor="end" fill="#888">{label}</text>;
}; };
const getFormattedNetworkMetric = (value) => {
if (typeof value !== "number" || isNaN(value)) return "0";
if (value >= 1024 ** 3) return `${(value / 1024 ** 3).toFixed(1)} GB/s`;
if (value >= 1024 ** 2) return `${(value / 1024 ** 2).toFixed(1)} MB/s`;
if (value >= 1024) return `${(value / 1024).toFixed(1)} KB/s`;
return `${Math.round(value)} B/s`;
};
const NetworkCharts = ({ eth0Data, dateRange }) => { const NetworkCharts = ({ eth0Data, dateRange }) => {
const theme = useTheme(); const theme = useTheme();
const textColor = theme.palette.primary.contrastTextTertiary; const textColor = theme.palette.primary.contrastTextTertiary;
const charts = [ const charts = [
{ title: "eth0 Bytes/sec", key: "bytesPerSec", color: theme.palette.info.main, yTick: <BytesTick /> }, { title: "Bytes per second", key: "bytesPerSec", color: theme.palette.info.main, yTick: <BytesTick /> },
{ title: "eth0 Packets/sec", key: "packetsPerSec", color: theme.palette.success.main }, { title: "Packets per second", key: "packetsPerSec", color: theme.palette.success.main },
{ title: "eth0 Errors", key: "errors", color: theme.palette.error.main }, { title: "Errors", key: "errors", color: theme.palette.error.main },
{ title: "eth0 Drops", key: "drops", color: theme.palette.warning.main } { title: "Drops", key: "drops", color: theme.palette.warning.main }
]; ];
const formatYAxis = (key, value) => {
if (key === "bytesPerSec") {
// Format as MB/s or GB/s if large
if (value >= 1024 ** 3) return `${(value / 1024 ** 3).toFixed(1)} GB/s`;
if (value >= 1024 ** 2) return `${(value / 1024 ** 2).toFixed(1)} MB/s`;
if (value >= 1024) return `${(value / 1024).toFixed(1)} KB/s`;
return `${Math.round(value)} B/s`;
}
return Math.round(value).toLocaleString();
};
const CustomTick = ({ x, y, payload, chartKey }) => {
// Ensure value is always rounded for display
let value = payload.value;
if (typeof value === 'number') {
value = Math.round(value);
}
return (
<text x={x} y={y} textAnchor="end" fill="#888">
{formatYAxis(chartKey, value)}
</text>
);
};
const chartConfigs = charts.map((chart) => ({
data: eth0Data,
dataKeys: [chart.key],
heading: chart.title,
strokeColor: chart.color,
gradientStartColor: chart.color,
yTick: chart.yTick || <CustomTick chartKey={chart.key} />,
xTick: <TzTick dateRange={dateRange} />,
toolTip: (
<InfrastructureTooltip
dotColor={chart.color}
yKey={chart.key}
yLabel={chart.title}
dateRange={dateRange}
formatter={getFormattedNetworkMetric}
/>
),
}));
return ( return (
<Grid container spacing={3}> <Grid container spacing={3}>
{charts.map((chart) => ( {chartConfigs.map((config, idx) => (
<Grid item xs={12} md={6} key={chart.key}> <Grid item xs={12} md={6} key={config.heading}>
<Card variant="outlined"> <Card variant="outlined">
<CardContent> <CardContent>
<Typography variant="h6" sx={{ color: textColor }} mb={2}> <Typography variant="h6" sx={{ color: textColor }} mb={2}>
{chart.title} {config.heading}
</Typography> </Typography>
<AreaChart <AreaChart
data={eth0Data} data={config.data}
dataKeys={[chart.key]} dataKeys={config.dataKeys}
xKey="time" xKey="time"
yTick={chart.yTick || null} yTick={config.yTick}
xTick={<TzTick dateRange={dateRange} />} xTick={config.xTick}
strokeColor={chart.color} strokeColor={config.strokeColor}
gradient gradient
gradientStartColor={chart.color} gradientStartColor={config.gradientStartColor}
gradientEndColor="#fff" gradientEndColor="#fff"
height={200} height={200}
customTooltip={config.toolTip}
/> />
</CardContent> </CardContent>
</Card> </Card>
@@ -7,76 +7,78 @@ import StatBox from "../../../../../Components/StatBox";
import { Typography } from "@mui/material"; import { Typography } from "@mui/material";
const INTERFACE_LABELS = { const INTERFACE_LABELS = {
en0: "Ethernet/Wi-Fi (Primary)", en0: "Ethernet/Wi-Fi (Primary)",
wlan0: "Wi-Fi (Secondary)", wlan0: "Wi-Fi (Secondary)",
}; };
function formatBytes(bytes) { function formatBytes(bytes) {
if (bytes === 0 || bytes == null) return "0 B"; if (bytes === 0 || bytes == null) return "0 B";
const k = 1024; const k = 1024;
const sizes = ["B", "KB", "MB", "GB", "TB"]; const sizes = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(k)); const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`; return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
} }
// Format numbers with commas // Format numbers with commas
function formatNumber(num) { function formatNumber(num) {
return num != null ? num.toLocaleString() : "0"; return num != null ? num.toLocaleString() : "0";
} }
const NetworkStatBoxes = ({ shouldRender, net }) => { const NetworkStatBoxes = ({ shouldRender, net }) => {
const filtered = net?.filter( const filtered =
(iface) => iface.name === "en0" || iface.name === "wlan0" net?.filter((iface) => iface.name === "en0" || iface.name === "wlan0") || [];
) || [];
if (!net?.length) { if (!net?.length) {
return <Typography>No network stats available.</Typography>; return <Typography>No network stats available.</Typography>;
} }
return ( return (
<StatusBoxes shouldRender={shouldRender} flexWrap="wrap"> <StatusBoxes
{filtered.map((iface) => ( shouldRender={shouldRender}
<> flexWrap="wrap"
<StatBox >
heading={`${INTERFACE_LABELS[iface.name] || iface.name} - Bytes Sent`} {filtered.map((iface) => (
subHeading={formatBytes(iface.bytes_sent)} <>
icon={DataUsageIcon} <StatBox
iconProps={{ color: "action" }} heading={`${INTERFACE_LABELS[iface.name] || iface.name} - Bytes Sent`}
/> subHeading={formatBytes(iface.bytes_sent)}
<StatBox icon={DataUsageIcon}
heading="Bytes Received" iconProps={{ color: "action" }}
subHeading={formatBytes(iface.bytes_recv)} />
icon={DataUsageIcon} <StatBox
iconProps={{ color: "action", sx: { transform: "rotate(180deg)" } }} heading="Bytes Received"
/> subHeading={formatBytes(iface.bytes_recv)}
<StatBox icon={DataUsageIcon}
heading="Packets Sent" iconProps={{ color: "action", sx: { transform: "rotate(180deg)" } }}
subHeading={formatNumber(iface.packets_sent)} />
icon={NetworkCheckIcon} <StatBox
iconProps={{ color: "action" }} heading="Packets Sent"
/> subHeading={formatNumber(iface.packets_sent)}
<StatBox icon={NetworkCheckIcon}
heading="Packets Received" iconProps={{ color: "action" }}
subHeading={formatNumber(iface.packets_recv)} />
icon={NetworkCheckIcon} <StatBox
iconProps={{ color: "action", sx: { transform: "rotate(180deg)" } }} heading="Packets Received"
/> subHeading={formatNumber(iface.packets_recv)}
<StatBox icon={NetworkCheckIcon}
heading="Errors In" iconProps={{ color: "action", sx: { transform: "rotate(180deg)" } }}
subHeading={formatNumber(iface.err_in)} />
icon={ErrorOutlineIcon} <StatBox
iconProps={{ color: "error" }} heading="Errors In"
/> subHeading={formatNumber(iface.err_in)}
<StatBox icon={ErrorOutlineIcon}
heading="Errors Out" iconProps={{ color: "error" }}
subHeading={formatNumber(iface.err_out)} />
icon={ErrorOutlineIcon} <StatBox
iconProps={{ color: "error" }} heading="Errors Out"
/> subHeading={formatNumber(iface.err_out)}
</> icon={ErrorOutlineIcon}
))} iconProps={{ color: "error" }}
</StatusBoxes> />
); </>
))}
</StatusBoxes>
);
}; };
export default NetworkStatBoxes; export default NetworkStatBoxes;
@@ -3,98 +3,105 @@ import NetworkCharts from "./NetworkCharts";
import MonitorTimeFrameHeader from "../../../../../Components/MonitorTimeFrameHeader"; import MonitorTimeFrameHeader from "../../../../../Components/MonitorTimeFrameHeader";
function filterByDateRange(data, dateRange) { function filterByDateRange(data, dateRange) {
if (!Array.isArray(data)) return []; if (!Array.isArray(data)) return [];
const now = Date.now(); const now = Date.now();
let cutoff; let cutoff;
switch (dateRange) { switch (dateRange) {
case "recent": case "recent":
cutoff = now - 2 * 60 * 60 * 1000; // last 2 hours cutoff = now - 2 * 60 * 60 * 1000; // last 2 hours
break; break;
case "day": case "day":
cutoff = now - 24 * 60 * 60 * 1000; // last 24 hours cutoff = now - 24 * 60 * 60 * 1000; // last 24 hours
break; break;
case "week": case "week":
cutoff = now - 7 * 24 * 60 * 60 * 1000; // last 7 days cutoff = now - 7 * 24 * 60 * 60 * 1000; // last 7 days
break; break;
case "month": case "month":
cutoff = now - 30 * 24 * 60 * 60 * 1000; // last 30 days cutoff = now - 30 * 24 * 60 * 60 * 1000; // last 30 days
break; break;
default: default:
cutoff = 0; cutoff = 0;
} }
return data.filter((d) => new Date(d.time).getTime() >= cutoff); return data.filter((d) => new Date(d.time).getTime() >= cutoff);
} }
const Network = ({ net, checks, isLoading, dateRange, setDateRange }) => { const Network = ({ net, checks, isLoading, dateRange, setDateRange }) => {
const eth0Data = getEth0TimeSeries(checks); const eth0Data = getEth0TimeSeries(checks);
const xAxisFormatter = getXAxisFormatter(checks); const xAxisFormatter = getXAxisFormatter(checks);
const filteredEth0Data = filterByDateRange(eth0Data, dateRange); const filteredEth0Data = filterByDateRange(eth0Data, dateRange);
return ( return (
<> <>
<NetworkStatBoxes shouldRender={!isLoading} net={net} /> <NetworkStatBoxes
<MonitorTimeFrameHeader shouldRender={!isLoading}
isLoading={isLoading} net={net}
dateRange={dateRange} />
setDateRange={setDateRange} <MonitorTimeFrameHeader
/> isLoading={isLoading}
<NetworkCharts eth0Data={filteredEth0Data} xAxisFormatter={xAxisFormatter} /> dateRange={dateRange}
</> setDateRange={setDateRange}
); />
<NetworkCharts
eth0Data={filteredEth0Data}
xAxisFormatter={xAxisFormatter}
/>
</>
);
}; };
export default Network; export default Network;
/* ---------- Helper functions ---------- */ /* ---------- Helper functions ---------- */
function getEth0TimeSeries(checks) { function getEth0TimeSeries(checks) {
const sorted = [...(checks || [])].sort((a, b) => new Date(a._id) - new Date(b._id)); const sorted = [...(checks || [])].sort((a, b) => new Date(a._id) - new Date(b._id));
const series = []; const series = [];
let prev = null; let prev = null;
for (const check of sorted) { for (const check of sorted) {
const eth = (check.net || []).find((iface) => iface.name === "en0"); const eth = (check.net || []).find((iface) => iface.name === "en0");
if (!eth) { if (!eth) {
prev = check; prev = check;
continue; continue;
} }
if (prev) { if (prev) {
const prevEth = (prev.net || []).find((iface) => iface.name === "en0"); const prevEth = (prev.net || []).find((iface) => iface.name === "en0");
const t1 = new Date(check._id); const t1 = new Date(check._id);
const t0 = new Date(prev._id); const t0 = new Date(prev._id);
if (!prevEth || isNaN(t1) || isNaN(t0)) { if (!prevEth || isNaN(t1) || isNaN(t0)) {
prev = check; prev = check;
continue; continue;
} }
const dt = (t1 - t0) / 1000; const dt = (t1 - t0) / 1000;
if (dt > 0) { if (dt > 0) {
series.push({ series.push({
time: check._id, time: check._id,
bytesPerSec: (eth.bytesSent - prevEth.bytesSent) / dt, bytesPerSec: (eth.bytesSent - prevEth.bytesSent) / dt,
packetsPerSec: (eth.packetsSent - prevEth.packetsSent) / dt, packetsPerSec: (eth.packetsSent - prevEth.packetsSent) / dt,
errors: (eth.errIn ?? 0) + (eth.errOut ?? 0), errors: (eth.errIn ?? 0) + (eth.errOut ?? 0),
drops: (eth.dropIn ?? 0) + (eth.dropOut ?? 0), drops: (eth.dropIn ?? 0) + (eth.dropOut ?? 0),
}); });
} }
} }
prev = check; prev = check;
} }
return series; return series;
} }
function getXAxisFormatter(checks) { function getXAxisFormatter(checks) {
if (!checks || checks.length === 0) return (val) => val; if (!checks || checks.length === 0) return (val) => val;
const sorted = [...checks].sort((a, b) => new Date(a._id) - new Date(b._id)); const sorted = [...checks].sort((a, b) => new Date(a._id) - new Date(b._id));
const first = new Date(sorted[0]._id); const first = new Date(sorted[0]._id);
const last = new Date(sorted[sorted.length - 1]._id); const last = new Date(sorted[sorted.length - 1]._id);
const diffDays = (last - first) / (1000 * 60 * 60 * 24); const diffDays = (last - first) / (1000 * 60 * 60 * 24);
return diffDays > 2 return diffDays > 2
? (val) => new Date(val).toLocaleDateString(undefined, { month: "short", day: "numeric" }) ? (val) =>
: (val) => new Date(val).toLocaleDateString(undefined, { month: "short", day: "numeric" })
new Date(val).toLocaleTimeString(undefined, { : (val) =>
hour: "2-digit", new Date(val).toLocaleTimeString(undefined, {
minute: "2-digit", hour: "2-digit",
hour12: false, minute: "2-digit",
}); hour12: false,
});
} }