feat(speed): better network speed readability

This commit is contained in:
Loongphy 2024-09-28 20:40:40 +08:00
parent f537663892
commit 92497c62f5
2 changed files with 31 additions and 7 deletions

View File

@ -7,7 +7,7 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn, formatNezhaInfo } from "@/lib/utils";
import { cn, formatNezhaInfo, formatNetworkSpeed } from "@/lib/utils";
import ServerCardPopover from "./ServerCardPopover";
import getUnicodeFlagIcon from "country-flag-icons/unicode";
import { env } from "next-runtime-env";
@ -21,6 +21,9 @@ export default function ServerCard({
const { name, country_code, online, cpu, up, down, mem, stg, ...props } =
formatNezhaInfo(serverInfo);
const formattedUpSpeed = formatNetworkSpeed(up);
const formattedDownSpeed = formatNetworkSpeed(down);
const showFlag = env("NEXT_PUBLIC_ShowFlag") === "true";
return online ? (
@ -89,8 +92,8 @@ export default function ServerCard({
{/* 设置固定宽度 */}
<p className="text-xs text-muted-foreground">{t("Upload")}</p>
<div className="flex items-center text-xs font-semibold">
{up.toFixed(2)}
Mb/s
{formattedUpSpeed.value}
{formattedUpSpeed.unit}
</div>
</div>
<div className={"flex w-14 flex-col"}>
@ -98,8 +101,8 @@ export default function ServerCard({
{/* 设置固定宽度 */}
<p className="text-xs text-muted-foreground">{t("Download")}</p>
<div className="flex items-center text-xs font-semibold">
{down.toFixed(2)}
Mb/s
{formattedDownSpeed.value}
{formattedDownSpeed.unit}
</div>
</div>
</section>

View File

@ -10,8 +10,8 @@ export function formatNezhaInfo(serverInfo: NezhaAPISafe) {
return {
...serverInfo,
cpu: serverInfo.status.CPU,
up: serverInfo.status.NetOutSpeed / 1024 / 1024,
down: serverInfo.status.NetInSpeed / 1024 / 1024,
up: serverInfo.status.NetOutSpeed,
down: serverInfo.status.NetInSpeed,
online: serverInfo.online_status,
mem: (serverInfo.status.MemUsed / serverInfo.host.MemTotal) * 100,
stg: (serverInfo.status.DiskUsed / serverInfo.host.DiskTotal) * 100,
@ -19,6 +19,27 @@ export function formatNezhaInfo(serverInfo: NezhaAPISafe) {
};
}
interface FormattedSpeed {
value: number;
unit: string;
}
export function formatNetworkSpeed(bytesPerSecond: number): FormattedSpeed {
const units = ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s'];
let speed = bytesPerSecond;
let unitIndex = 0;
while (speed >= 1024 && unitIndex < units.length - 1) {
speed /= 1024;
unitIndex++;
}
return {
value: parseFloat(speed.toFixed(2)),
unit: units[unitIndex]
};
}
export function formatBytes(bytes: number, decimals: number = 2) {
if (!+bytes) return "0 Bytes";