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