feat: polish release v2 experience (#6800)
This commit is contained in:
1 parent
925b0fb801
commit
a4a903d7c3
295 files changed
+10627
-7115
No files matched your search
@@ -20,6 +20,7 @@ import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useOptionalBoard } from "@homarr/boards/context";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import type { CustomWidgetOption } from "@homarr/custom-widgets/core";
|
||||
import { normalizeCustomWidgetOptions, validateCustomWidgetOptions } from "@homarr/custom-widgets/core";
|
||||
import { CustomWidgetCodeEditor } from "@homarr/custom-widgets/workbench";
|
||||
@@ -355,7 +356,3 @@ function getByPath(value: unknown, path: string): unknown {
|
||||
.filter(Boolean)
|
||||
.reduce<unknown>((current, segment) => (isRecord(current) ? current[segment] : undefined), value);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -2,13 +2,45 @@
|
||||
|
||||
import { NumberInput } from "@mantine/core";
|
||||
|
||||
import { useSettings } from "@homarr/settings";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
const KIBIBYTE = 1024;
|
||||
const KILOBYTE = 1000;
|
||||
|
||||
export const WidgetNumberInput = ({ property, kind, options }: CommonWidgetInputProps<"number">) => {
|
||||
const t = useWidgetInputTranslation(kind, property);
|
||||
const form = useFormContext();
|
||||
const { byteUnitSystem } = useSettings();
|
||||
const inputProps = form.getInputProps(`options.${property}`);
|
||||
|
||||
let value = inputProps.value;
|
||||
let onChange = inputProps.onChange;
|
||||
let suffix: string | undefined;
|
||||
let decimalScale: number | undefined;
|
||||
|
||||
if (options.storedUnit === "kibibytesPerSecond") {
|
||||
let bytesPerDisplayedUnit = KIBIBYTE;
|
||||
suffix = " KiB/s";
|
||||
if (byteUnitSystem === "decimal") {
|
||||
bytesPerDisplayedUnit = KILOBYTE;
|
||||
suffix = " KB/s";
|
||||
}
|
||||
|
||||
const displayFactor = KIBIBYTE / bytesPerDisplayedUnit;
|
||||
if (typeof value === "number") value *= displayFactor;
|
||||
onChange = (nextValue: string | number) => {
|
||||
if (typeof nextValue !== "number") {
|
||||
inputProps.onChange(nextValue);
|
||||
return;
|
||||
}
|
||||
inputProps.onChange(nextValue / displayFactor);
|
||||
};
|
||||
decimalScale = 6;
|
||||
}
|
||||
|
||||
return (
|
||||
<NumberInput
|
||||
@@ -17,7 +49,11 @@ export const WidgetNumberInput = ({ property, kind, options }: CommonWidgetInput
|
||||
min={options.validate.minValue ?? undefined}
|
||||
max={options.validate.maxValue ?? undefined}
|
||||
step={options.step}
|
||||
{...form.getInputProps(`options.${property}`)}
|
||||
suffix={suffix}
|
||||
decimalScale={decimalScale}
|
||||
{...inputProps}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -3,8 +3,8 @@
|
||||
import { Avatar, Badge, Card, Group, ScrollArea, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatByteRate } from "@homarr/common";
|
||||
import { getIconUrl } from "@homarr/definitions";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
@@ -49,6 +49,7 @@ const ArchiveTeamWarriorWidgetContent = ({
|
||||
const t = useI18n("widget.archiveTeamWarrior");
|
||||
const tWidgetCommon = useI18n("widget.common");
|
||||
const locale = useCurrentIntlLocale();
|
||||
const { formatBytes, formatByteRate } = useByteFormatter();
|
||||
const [data] = clientApi.widget.archiveTeamWarrior.getStatus.useSuspenseQuery({ integrationId });
|
||||
|
||||
const status = data.status;
|
||||
@@ -61,6 +62,7 @@ const ArchiveTeamWarriorWidgetContent = ({
|
||||
{ label: t("metric.failed"), value: status.counts.failed },
|
||||
...(layout.showSecondaryCounts ? [{ label: t("metric.canceled"), value: status.counts.canceled }] : []),
|
||||
];
|
||||
const formatBandwidth = (value?: number) => formatByteRate(Math.round(value ?? 0));
|
||||
|
||||
return (
|
||||
<Stack p="xs" gap={layout.gap} h="100%" style={{ overflow: "hidden" }}>
|
||||
@@ -117,12 +119,12 @@ const ArchiveTeamWarriorWidgetContent = ({
|
||||
)}
|
||||
{status.bandwidth?.received !== undefined && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("sessionReceived", { value: formatBandwidth(status.bandwidth.received) })}
|
||||
{t("sessionReceived", { value: formatBytes(Math.round(status.bandwidth.received)) })}
|
||||
</Text>
|
||||
)}
|
||||
{status.bandwidth?.sent !== undefined && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("sessionSent", { value: formatBandwidth(status.bandwidth.sent) })}
|
||||
{t("sessionSent", { value: formatBytes(Math.round(status.bandwidth.sent)) })}
|
||||
</Text>
|
||||
)}
|
||||
{status.bandwidth?.session_id && (
|
||||
@@ -141,13 +143,7 @@ const ArchiveTeamWarriorWidgetContent = ({
|
||||
{status.items.map((item) => {
|
||||
const itemStatusKey = getStatusKey(item.status);
|
||||
return (
|
||||
<Card
|
||||
key={item.id}
|
||||
withBorder
|
||||
p="xs"
|
||||
bg="transparent"
|
||||
style={{ borderColor: neutralSurfaceBorder }}
|
||||
>
|
||||
<Card key={item.id} withBorder p="xs" bg="transparent" style={{ borderColor: neutralSurfaceBorder }}>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Stack gap={0} miw={0}>
|
||||
<Text size="sm" fw={600} lineClamp={1}>
|
||||
@@ -203,10 +199,7 @@ export const getArchiveCompactLayout = (width: number, height: number, isAdvance
|
||||
} as const;
|
||||
};
|
||||
|
||||
const formatBandwidth = (value?: number) => formatByteRate(Math.round(value ?? 0));
|
||||
|
||||
const neutralSurfaceBorder =
|
||||
"rgb(from var(--mantine-color-default-border) r g b / calc(var(--opacity, 1) * 0.45))";
|
||||
const neutralSurfaceBorder = "rgb(from var(--mantine-color-default-border) r g b / calc(var(--opacity, 1) * 0.45))";
|
||||
|
||||
type WarriorStatusKey = "running" | "completed" | "failed" | "canceled" | "stopped" | "idle" | "unknown";
|
||||
|
||||
|
||||
@@ -4,8 +4,9 @@ import { Badge, Box, Group, ScrollArea, SimpleGrid, Stack, Text } from "@mantine
|
||||
import { getQueryKey } from "@trpc/react-query";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatBytes, formatDuration } from "@homarr/common";
|
||||
import { formatDuration } from "@homarr/common";
|
||||
import type { AudiobookshelfDashboardData } from "@homarr/integrations/types";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
|
||||
import { WidgetEmptyState } from "../common/empty-state";
|
||||
import { IntegrationErrorIndicator } from "../common/integration-error-indicator";
|
||||
@@ -22,6 +23,7 @@ export default function AudioStatsWidget({
|
||||
displayMode = "compact",
|
||||
widgetRuntimeRef,
|
||||
}: WidgetComponentProps<"audioStats">) {
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const statsInput = { integrationId: integrationIds[0] ?? "" };
|
||||
const { data: response, error: statsError } = clientApi.widget.audioStats.getStats.useQuery(statsInput);
|
||||
const streamsInput = { integrationIds: [statsInput.integrationId], showOnlyPlaying: true };
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { LucideIcon } from "lucide-react";
|
||||
import { Activity, Battery, Cpu, HardDrive, MemoryStick, Monitor, Network, Server, Thermometer } from "lucide-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
@@ -244,7 +245,6 @@ const unitSuffixMap: Record<string, string> = {
|
||||
GPU: "%",
|
||||
Battery: "%",
|
||||
Temperature: "°",
|
||||
Bandwidth: " MB/s",
|
||||
"Load Average": "",
|
||||
LoadAvg1: "",
|
||||
LoadAvg5: "",
|
||||
@@ -254,9 +254,14 @@ const unitSuffixMap: Record<string, string> = {
|
||||
|
||||
function AlertRow({ name, value, min, systemName, integrationName, triggered, isAdvanced }: AlertRowProps) {
|
||||
const t = useI18n("widget.beszelAlerts");
|
||||
const { formatByteRate } = useByteFormatter();
|
||||
const Icon = alertIconMap[name] ?? Server;
|
||||
const suffix = unitSuffixMap[name] ?? "";
|
||||
let description = t("alertDescription.threshold", { value: `${value}${suffix}`, minutes: min });
|
||||
let formattedValue = `${value}${suffix}`;
|
||||
if (name === "Bandwidth") {
|
||||
formattedValue = formatByteRate(value * 1024 ** 2);
|
||||
}
|
||||
let description = t("alertDescription.threshold", { value: formattedValue, minutes: min });
|
||||
if (name === "Status") {
|
||||
description = t("alertDescription.statusDuration", { minutes: min });
|
||||
}
|
||||
|
||||
@@ -31,9 +31,9 @@ import { IconServerOff } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import { invariantTechnicalLabels } from "@homarr/definitions";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
@@ -42,14 +42,7 @@ import classes from "./component.module.css";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import type { BeszelSystemRow } from "../beszel/_shared/types";
|
||||
import { statusColorMap, thresholdColor } from "../beszel/_shared/colors";
|
||||
import {
|
||||
formatByteRate,
|
||||
formatLoadAvg,
|
||||
formatPercent,
|
||||
formatTemp,
|
||||
formatUptime,
|
||||
getProgressTrackSize,
|
||||
} from "../beszel/_shared/format";
|
||||
import { formatLoadAvg, formatPercent, formatTemp, formatUptime, getProgressTrackSize } from "../beszel/_shared/format";
|
||||
import { useBeszelFilteredSystems } from "../beszel/_shared/hooks";
|
||||
import { IntegrationErrorIndicator } from "../common/integration-error-indicator";
|
||||
import { getUsableWidgetQueryData } from "../common/query-state";
|
||||
@@ -198,6 +191,7 @@ type BeszelMetricRenderer = {
|
||||
t: SystemCardProps["t"],
|
||||
size: SizeConfig,
|
||||
tCommon: SystemCardProps["tCommon"],
|
||||
formatByteRate: (bytes: number) => string,
|
||||
) => React.ReactNode;
|
||||
visible: (system: BeszelSystemRow, options: SystemCardProps["options"], advanced: boolean) => boolean;
|
||||
};
|
||||
@@ -278,7 +272,13 @@ const metricRenderers: BeszelMetricRenderer[] = [
|
||||
},
|
||||
{
|
||||
key: "showNet",
|
||||
render: (s: BeszelSystemRow, t: SystemCardProps["t"], sz: SizeConfig) => (
|
||||
render: (
|
||||
s: BeszelSystemRow,
|
||||
t: SystemCardProps["t"],
|
||||
sz: SizeConfig,
|
||||
_tCommon: SystemCardProps["tCommon"],
|
||||
formatByteRate: (bytes: number) => string,
|
||||
) => (
|
||||
<MetricRow
|
||||
key="net"
|
||||
icon={<Network style={zoomCompensatedSize(sz.iconSize)} />}
|
||||
@@ -378,6 +378,7 @@ const SystemCard = ({
|
||||
isAdvanced,
|
||||
onClick,
|
||||
}: SystemCardProps) => {
|
||||
const { formatByteRate, formatBytes } = useByteFormatter();
|
||||
const enabledMetrics = metricRenderers.filter((metric) => metric.visible(system, options, isAdvanced));
|
||||
const visibleMetrics = enabledMetrics.slice(0, maxMetrics);
|
||||
const hiddenMetricCount = enabledMetrics.length - visibleMetrics.length;
|
||||
@@ -429,7 +430,7 @@ const SystemCard = ({
|
||||
)}
|
||||
|
||||
<Stack gap={0} style={{ flex: 1 }} justify="space-evenly">
|
||||
{visibleMetrics.map((m) => m.render(system, t, size, tCommon))}
|
||||
{visibleMetrics.map((m) => m.render(system, t, size, tCommon, formatByteRate))}
|
||||
</Stack>
|
||||
{hiddenMetricCount > 0 && (
|
||||
<Text size="xs" c="dimmed" ta="right">
|
||||
|
||||
@@ -21,10 +21,10 @@ import { useSession } from "@homarr/auth/client";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
import { constructBoardPermissions } from "@homarr/auth/shared";
|
||||
import { useOptionalBoard } from "@homarr/boards/context";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import { invariantTechnicalLabels } from "@homarr/definitions";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
@@ -33,14 +33,7 @@ import { getUsableWidgetQueryData } from "../common/query-state";
|
||||
import { usePersistedTableLayout, useTableLayoutPersistence } from "../common/use-persisted-table-layout";
|
||||
import type { BeszelSystemRow } from "../beszel/_shared/types";
|
||||
import { loadAvgColor, statusColorMap, thresholdColor } from "../beszel/_shared/colors";
|
||||
import {
|
||||
formatByteRate,
|
||||
formatLoadAvg,
|
||||
formatPercent,
|
||||
formatTemp,
|
||||
formatUptime,
|
||||
getProgressTrackSize,
|
||||
} from "../beszel/_shared/format";
|
||||
import { formatLoadAvg, formatPercent, formatTemp, formatUptime, getProgressTrackSize } from "../beszel/_shared/format";
|
||||
import { useBeszelFilteredSystems } from "../beszel/_shared/hooks";
|
||||
import { IntegrationErrorIndicator } from "../common/integration-error-indicator";
|
||||
import { BeszelSystemStatsModal } from "../beszel/_shared/system-stats-modal";
|
||||
@@ -131,6 +124,7 @@ export default function BeszelSystemTableWidget({
|
||||
const { openModal } = useModalAction(BeszelSystemStatsModal);
|
||||
const board = useOptionalBoard();
|
||||
const { data: session } = useSession();
|
||||
const { formatByteRate, formatBytes } = useByteFormatter();
|
||||
const hasChangeAccess = board ? constructBoardPermissions(board, session).hasChangeAccess : false;
|
||||
const systemsQuery = clientApi.widget.beszel.getSystems.useQuery({ integrationIds });
|
||||
const systemsData = getUsableWidgetQueryData(systemsQuery);
|
||||
@@ -421,7 +415,7 @@ export default function BeszelSystemTableWidget({
|
||||
];
|
||||
|
||||
return cols.filter(Boolean) as DataTableColumn<SystemRowWithKey>[];
|
||||
}, [tBeszel, tCommon, size, visibleMetricKeys, isAdvanced]);
|
||||
}, [formatByteRate, formatBytes, tBeszel, tCommon, size, visibleMetricKeys, isAdvanced]);
|
||||
|
||||
const { effectiveColumns, storeKey } = usePersistedTableLayout({
|
||||
columns,
|
||||
|
||||
@@ -2,7 +2,9 @@ import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { BeszelSystemStatsRecord } from "@homarr/integrations/types";
|
||||
|
||||
import { buildDiskChartData, padLiveTimeGrid } from "./chart";
|
||||
import { buildDiskChartData, normalizeBeszelByteRate, padLiveTimeGrid } from "./chart";
|
||||
|
||||
const GIBIBYTE = 1024 ** 3;
|
||||
|
||||
const record = (
|
||||
created: string,
|
||||
@@ -30,7 +32,7 @@ const record = (
|
||||
});
|
||||
|
||||
describe("buildDiskChartData", () => {
|
||||
test("keeps root and extra filesystem usage in GiB without stacking or byte conversion", () => {
|
||||
test("normalizes root and extra filesystem usage to bytes without stacking", () => {
|
||||
const data = buildDiskChartData(
|
||||
[
|
||||
record("2026-07-11T13:46:00.000Z", 455.81, {
|
||||
@@ -45,7 +47,12 @@ describe("buildDiskChartData", () => {
|
||||
);
|
||||
|
||||
expect(data).toHaveLength(1);
|
||||
expect(data[0]).toMatchObject({ Root: 455.81, sda: 1656.45, sdb: 3936.86, sdc: 1589.84 });
|
||||
expect(data[0]).toMatchObject({
|
||||
Root: 455.81 * GIBIBYTE,
|
||||
sda: 1656.45 * GIBIBYTE,
|
||||
sdb: 3936.86 * GIBIBYTE,
|
||||
sdc: 1589.84 * GIBIBYTE,
|
||||
});
|
||||
});
|
||||
|
||||
test("uses zero for a filesystem missing from an individual sample and orders historical records oldest first", () => {
|
||||
@@ -60,12 +67,23 @@ describe("buildDiskChartData", () => {
|
||||
);
|
||||
|
||||
expect(data.map((point) => ({ Root: point.Root, sda: point.sda }))).toEqual([
|
||||
{ Root: 1, sda: 0 },
|
||||
{ Root: 2, sda: 4 },
|
||||
{ Root: GIBIBYTE, sda: 0 },
|
||||
{ Root: 2 * GIBIBYTE, sda: 4 * GIBIBYTE },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeBeszelByteRate", () => {
|
||||
test("converts legacy MiB/s values to bytes/s", () => {
|
||||
expect(normalizeBeszelByteRate(undefined, 1.5)).toBe(1.5 * 1024 ** 2);
|
||||
});
|
||||
|
||||
test("keeps the preferred bytes/s value authoritative, including zero", () => {
|
||||
expect(normalizeBeszelByteRate(0, 1.5)).toBe(0);
|
||||
expect(normalizeBeszelByteRate(1_500_000, 1.5)).toBe(1_500_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("padLiveTimeGrid", () => {
|
||||
test("keeps a fixed 60-second window with the newest sample at the right edge", () => {
|
||||
const data = padLiveTimeGrid([{ time: "13:51:30", rawTime: "2026-07-11T13:51:30.217Z", CPU: 18.07 }]);
|
||||
|
||||
@@ -204,13 +204,19 @@ export const useContainerNames = (containerStats: BeszelContainerStatsRecord[] |
|
||||
|
||||
type ContainerExtractor = (container: BeszelContainerStatsRecord["stats"][number] | undefined) => number;
|
||||
|
||||
// c = CPU (%), m = memory (MB), b = bandwidth [sent,recv] (bytes/s), ns/nr = legacy net (bytes/s)
|
||||
const MB = 1024 * 1024;
|
||||
// c = CPU (%), m = memory (MiB), b = bandwidth [sent,recv] (bytes/s), ns/nr = legacy net (MiB/s)
|
||||
const MEBIBYTE = 1024 * 1024;
|
||||
const GIBIBYTE = 1024 * MEBIBYTE;
|
||||
|
||||
export const normalizeBeszelByteRate = (
|
||||
bytesPerSecond: number | undefined,
|
||||
legacyMebibytesPerSecond: number | undefined,
|
||||
): number => bytesPerSecond ?? (legacyMebibytesPerSecond ?? 0) * MEBIBYTE;
|
||||
|
||||
const defaultContainerExtractors: Record<string, ContainerExtractor> = {
|
||||
cpu: (c) => c?.c ?? 0,
|
||||
memory: (c) => (c?.m ?? 0) * MB,
|
||||
network: (c) => (c?.b ? c.b[0] + c.b[1] : (c?.ns ?? 0) + (c?.nr ?? 0)),
|
||||
memory: (c) => (c?.m ?? 0) * MEBIBYTE,
|
||||
network: (c) => normalizeBeszelByteRate(c?.b?.[0], c?.ns) + normalizeBeszelByteRate(c?.b?.[1], c?.nr),
|
||||
};
|
||||
|
||||
export const useDiskChartData = (
|
||||
@@ -238,11 +244,11 @@ export const buildDiskChartData = (
|
||||
const point: Record<string, unknown> = {
|
||||
time: fmt(record.created),
|
||||
rawTime: record.created,
|
||||
[rootSeriesName]: record.stats.du,
|
||||
[rootSeriesName]: record.stats.du * GIBIBYTE,
|
||||
};
|
||||
const efs = record.stats.efs ?? {};
|
||||
for (const path of efsPaths) {
|
||||
point[path] = efs[path]?.du ?? 0;
|
||||
point[path] = (efs[path]?.du ?? 0) * GIBIBYTE;
|
||||
}
|
||||
return point;
|
||||
});
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { chartAxisFormatters, formatGB, getProgressTrackSize } from "./format";
|
||||
import { formatByteRate, formatBytes } from "@homarr/common";
|
||||
|
||||
import { createByteChartAxisFormatters, getProgressTrackSize } from "./format";
|
||||
|
||||
const GIBIBYTE = 1024 ** 3;
|
||||
const binaryAxisFormatters = createByteChartAxisFormatters(
|
||||
(bytes) => formatBytes(bytes, { unit: "binary" }),
|
||||
(bytes) => formatByteRate(bytes, { unit: "binary" }),
|
||||
);
|
||||
|
||||
describe("Beszel storage formatting", () => {
|
||||
test("keeps smaller values in GB", () => {
|
||||
expect(formatGB(455.81)).toBe("455.81 GB");
|
||||
expect(chartAxisFormatters.gb(455.81)).toBe("456G");
|
||||
test("formats canonical byte values with shared binary units", () => {
|
||||
expect(binaryAxisFormatters.bytes(455.81 * GIBIBYTE)).toBe("455.8GiB");
|
||||
});
|
||||
|
||||
test("promotes large GiB values to TB", () => {
|
||||
expect(formatGB(3323)).toBe("3.25 TB");
|
||||
expect(formatGB(3936.86)).toBe("3.84 TB");
|
||||
expect(chartAxisFormatters.gb(3323)).toBe("3.2T");
|
||||
test("promotes large canonical byte values to TiB", () => {
|
||||
expect(binaryAxisFormatters.bytes(3323 * GIBIBYTE)).toBe("3.2TiB");
|
||||
expect(binaryAxisFormatters.bytes(3936.86 * GIBIBYTE)).toBe("3.8TiB");
|
||||
});
|
||||
|
||||
test("maps progress sizes consistently", () => {
|
||||
|
||||
@@ -5,51 +5,23 @@ import relativeTime from "dayjs/plugin/relativeTime";
|
||||
dayjs.extend(duration);
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
const byteUnits = ["B", "KB", "MB", "GB", "TB"] as const;
|
||||
const rateUnits = ["B/s", "KB/s", "MB/s", "GB/s"] as const;
|
||||
|
||||
const formatScaled = (value: number, units: readonly string[], zeroLabel: string): string => {
|
||||
if (!value || !Number.isFinite(value)) return zeroLabel;
|
||||
const i = Math.max(0, Math.min(Math.floor(Math.log(Math.abs(value)) / Math.log(1024)), units.length - 1));
|
||||
const scaled = value / 1024 ** i;
|
||||
const decimals = scaled < 10 ? 2 : 1;
|
||||
return `${scaled.toFixed(decimals)} ${units[i] ?? ""}`;
|
||||
const compactByteLabel = (value: number, formatter: (value: number) => string): string => {
|
||||
if (!value || !Number.isFinite(value)) return "0";
|
||||
return formatter(Number(value)).replace(".0 ", "").replace(" ", "");
|
||||
};
|
||||
|
||||
const formatScaledCompact = (value: number, units: readonly string[], zeroLabel: string): string => {
|
||||
if (!value || !Number.isFinite(value)) return zeroLabel;
|
||||
const i = Math.max(0, Math.min(Math.floor(Math.log(Math.abs(value)) / Math.log(1024)), units.length - 1));
|
||||
const scaled = value / 1024 ** i;
|
||||
return `${scaled < 10 ? scaled.toFixed(1) : Math.round(scaled)}${units[i] ?? ""}`;
|
||||
};
|
||||
|
||||
export const formatByteRate = (value: number): string => formatScaled(value, rateUnits, "0 B/s");
|
||||
|
||||
export const formatStorageBytes = (bytes: number): string => formatScaled(bytes, byteUnits, "0 B");
|
||||
|
||||
export const formatGB = (value: number): string => {
|
||||
if (!value || !Number.isFinite(value)) return "0 GB";
|
||||
if (Math.abs(value) >= 1024) return `${(value / 1024).toFixed(2)} TB`;
|
||||
return `${value.toFixed(2)} GB`;
|
||||
};
|
||||
export const createByteChartAxisFormatters = (
|
||||
formatBytes: (bytes: number) => string,
|
||||
formatByteRate: (bytes: number) => string,
|
||||
) => ({
|
||||
bytes: (value: number) => compactByteLabel(value, formatBytes),
|
||||
rate: (value: number) => compactByteLabel(value, formatByteRate),
|
||||
});
|
||||
|
||||
export const formatPercent = (value: number): string => `${value.toFixed(1)}%`;
|
||||
|
||||
export const getProgressTrackSize = (size: "xs" | "sm"): number => (size === "xs" ? 6 : 9);
|
||||
|
||||
export const chartAxisFormatters = {
|
||||
percent: formatPercent,
|
||||
gb: (value: number) => {
|
||||
const numericValue = Number(value);
|
||||
if (!numericValue) return "0";
|
||||
if (Math.abs(numericValue) >= 1024) return `${(numericValue / 1024).toFixed(1)}T`;
|
||||
return `${numericValue.toFixed(0)}G`;
|
||||
},
|
||||
mb: (value: number) => (!value ? "0" : `${Number(value).toFixed(0)}M`),
|
||||
bytes: (value: number) => formatScaledCompact(Number(value), byteUnits, "0"),
|
||||
rate: (value: number) => formatScaledCompact(Number(value), rateUnits, "0"),
|
||||
} as const;
|
||||
|
||||
export const formatUptime = (seconds: number): string => dayjs.duration(seconds, "seconds").humanize();
|
||||
|
||||
export const formatTemp = (celsius: number | null, fahrenheit: boolean): string => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { IconPlugConnectedX, IconServerOff } from "@tabler/icons-react";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { invariantTechnicalLabels } from "@homarr/definitions";
|
||||
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
@@ -16,24 +17,19 @@ import type { BeszelTimePeriod } from "./chart";
|
||||
import {
|
||||
BeszelChartPanel,
|
||||
CPU_Y_AXIS_DOMAIN,
|
||||
normalizeBeszelByteRate,
|
||||
useContainerNames,
|
||||
useDiskChartData,
|
||||
useDockerChartData,
|
||||
useSystemChartData,
|
||||
} from "./chart";
|
||||
import { chartAxisFormatters, formatByteRate, formatGB, formatPercent, formatStorageBytes } from "./format";
|
||||
import { createByteChartAxisFormatters, formatPercent } from "./format";
|
||||
import { makeTooltipProps } from "./tooltip";
|
||||
import { useLiveStats } from "./use-live-stats";
|
||||
|
||||
const CHART_HEIGHT = 180;
|
||||
const MB = 1024 * 1024;
|
||||
const tooltips = {
|
||||
percent: makeTooltipProps(formatPercent),
|
||||
gigabytes: makeTooltipProps(formatGB, true),
|
||||
rate: makeTooltipProps(formatByteRate, true),
|
||||
percentTotal: makeTooltipProps(formatPercent, true),
|
||||
bytesTotal: makeTooltipProps(formatStorageBytes, true),
|
||||
};
|
||||
const MEBIBYTE = 1024 * 1024;
|
||||
const GIBIBYTE = 1024 * MEBIBYTE;
|
||||
|
||||
const ChartSkeleton = ({ height }: { height: number }) => (
|
||||
<Stack gap={4} style={{ minWidth: 0 }}>
|
||||
@@ -90,6 +86,21 @@ export function BeszelStatsView({
|
||||
const t = useI18n("widget.beszelSystemStats");
|
||||
const tBeszel = useI18n("widget.beszel");
|
||||
const locale = useCurrentIntlLocale();
|
||||
const { formatByteRate, formatBytes } = useByteFormatter();
|
||||
const byteAxisFormatters = useMemo(
|
||||
() => createByteChartAxisFormatters(formatBytes, formatByteRate),
|
||||
[formatByteRate, formatBytes],
|
||||
);
|
||||
const tooltips = useMemo(
|
||||
() => ({
|
||||
percent: makeTooltipProps(formatPercent),
|
||||
bytes: makeTooltipProps(formatBytes, true),
|
||||
rate: makeTooltipProps(formatByteRate, true),
|
||||
percentTotal: makeTooltipProps(formatPercent, true),
|
||||
bytesTotal: makeTooltipProps(formatBytes, true),
|
||||
}),
|
||||
[formatByteRate, formatBytes],
|
||||
);
|
||||
const showDocker = visibility.dockerCpu || visibility.dockerMemory || visibility.dockerNetwork;
|
||||
const isLive = timePeriod === "1m";
|
||||
const historicalQuery = clientApi.widget.beszel.getSystemStats.useQuery(
|
||||
@@ -108,16 +119,16 @@ export function BeszelStatsView({
|
||||
() => ({
|
||||
cpu: (s: { cpu: number }) => ({ [invariantTechnicalLabels.cpu]: s.cpu }),
|
||||
memory: (s: { mu: number; mb: number }) => ({
|
||||
[t("chart.memory.series")]: s.mu,
|
||||
[t("chart.memory.cache")]: s.mb ?? 0,
|
||||
[t("chart.memory.series")]: s.mu * GIBIBYTE,
|
||||
[t("chart.memory.cache")]: (s.mb ?? 0) * GIBIBYTE,
|
||||
}),
|
||||
diskIO: (s: { dr?: number; dw?: number }) => ({
|
||||
[t("chart.diskIO.read")]: (s.dr ?? 0) * MB,
|
||||
[t("chart.diskIO.write")]: (s.dw ?? 0) * MB,
|
||||
diskIO: (s: { dr?: number; dw?: number; dio?: [number, number] }) => ({
|
||||
[t("chart.diskIO.read")]: normalizeBeszelByteRate(s.dio?.[0], s.dr),
|
||||
[t("chart.diskIO.write")]: normalizeBeszelByteRate(s.dio?.[1], s.dw),
|
||||
}),
|
||||
network: (s: { ns?: number; nr?: number; b?: [number, number] }) => ({
|
||||
[t("chart.network.sent")]: s.b?.[0] ?? s.ns ?? 0,
|
||||
[t("chart.network.recv")]: s.b?.[1] ?? s.nr ?? 0,
|
||||
[t("chart.network.sent")]: normalizeBeszelByteRate(s.b?.[0], s.ns),
|
||||
[t("chart.network.recv")]: normalizeBeszelByteRate(s.b?.[1], s.nr),
|
||||
}),
|
||||
}),
|
||||
[t],
|
||||
@@ -288,7 +299,7 @@ export function BeszelStatsView({
|
||||
h: chartHeight,
|
||||
data: cpuData,
|
||||
series: series.cpu,
|
||||
yAxisFormatter: chartAxisFormatters.percent,
|
||||
yAxisFormatter: formatPercent,
|
||||
yAxisDomain: CPU_Y_AXIS_DOMAIN,
|
||||
tooltipProps: tooltips.percent,
|
||||
}}
|
||||
@@ -303,8 +314,8 @@ export function BeszelStatsView({
|
||||
data: memoryData,
|
||||
type: "stacked",
|
||||
series: series.memory,
|
||||
yAxisFormatter: chartAxisFormatters.gb,
|
||||
tooltipProps: tooltips.gigabytes,
|
||||
yAxisFormatter: byteAxisFormatters.bytes,
|
||||
tooltipProps: tooltips.bytes,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -317,8 +328,8 @@ export function BeszelStatsView({
|
||||
data: diskData,
|
||||
type: "stacked",
|
||||
series: diskSeries,
|
||||
yAxisFormatter: chartAxisFormatters.gb,
|
||||
tooltipProps: tooltips.gigabytes,
|
||||
yAxisFormatter: byteAxisFormatters.bytes,
|
||||
tooltipProps: tooltips.bytes,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -330,7 +341,7 @@ export function BeszelStatsView({
|
||||
h: chartHeight,
|
||||
data: diskIOData,
|
||||
series: series.diskIO,
|
||||
yAxisFormatter: chartAxisFormatters.rate,
|
||||
yAxisFormatter: byteAxisFormatters.rate,
|
||||
tooltipProps: tooltips.rate,
|
||||
}}
|
||||
/>
|
||||
@@ -343,7 +354,7 @@ export function BeszelStatsView({
|
||||
h: chartHeight,
|
||||
data: networkData,
|
||||
series: series.network,
|
||||
yAxisFormatter: chartAxisFormatters.rate,
|
||||
yAxisFormatter: byteAxisFormatters.rate,
|
||||
tooltipProps: tooltips.rate,
|
||||
}}
|
||||
/>
|
||||
@@ -359,7 +370,7 @@ export function BeszelStatsView({
|
||||
data: dockerCpuData,
|
||||
type: "stacked",
|
||||
series: containerSeries,
|
||||
yAxisFormatter: chartAxisFormatters.percent,
|
||||
yAxisFormatter: formatPercent,
|
||||
tooltipProps: tooltips.percentTotal,
|
||||
}}
|
||||
/>
|
||||
@@ -373,7 +384,7 @@ export function BeszelStatsView({
|
||||
data: dockerMemoryData,
|
||||
type: "stacked",
|
||||
series: containerSeries,
|
||||
yAxisFormatter: chartAxisFormatters.bytes,
|
||||
yAxisFormatter: byteAxisFormatters.bytes,
|
||||
tooltipProps: tooltips.bytesTotal,
|
||||
}}
|
||||
/>
|
||||
@@ -386,7 +397,7 @@ export function BeszelStatsView({
|
||||
h: chartHeight,
|
||||
data: dockerNetworkData,
|
||||
series: containerSeries,
|
||||
yAxisFormatter: chartAxisFormatters.rate,
|
||||
yAxisFormatter: byteAxisFormatters.rate,
|
||||
tooltipProps: tooltips.rate,
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -20,7 +20,12 @@ import { iconSizes } from "@homarr/ui";
|
||||
|
||||
import { formatLocalizedDate, formatLocalizedTime } from "../common/locale";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { clockTimeFormatShowsSeconds, clockTimeFormatUses12Hours, resolveClockTimeFormat } from "./format";
|
||||
import {
|
||||
clockTimeFormatShowsSeconds,
|
||||
clockTimeFormatUses12Hours,
|
||||
getTimeOfDayPhaseColor,
|
||||
resolveClockTimeFormat,
|
||||
} from "./format";
|
||||
import { TimeOfDayBar } from "./time-of-day-bar";
|
||||
import { ClockWeatherSummary } from "./weather-summary";
|
||||
import {
|
||||
@@ -31,7 +36,7 @@ import {
|
||||
humanizeTimeZone,
|
||||
maximumWorldClockCities,
|
||||
} from "./world-clock";
|
||||
import type { TimeOfDayPhase, WorldClockTime } from "./world-clock";
|
||||
import type { WorldClockTime } from "./world-clock";
|
||||
|
||||
interface AdvancedClockViewProps {
|
||||
now: Date;
|
||||
@@ -66,11 +71,7 @@ export const AdvancedClockView = ({
|
||||
.map((city) => createWorldClockTime({ city, now, primaryTime }));
|
||||
|
||||
return (
|
||||
<ScrollArea
|
||||
h="100%"
|
||||
w="100%"
|
||||
aria-label={t("worldClock.advancedLabel")}
|
||||
>
|
||||
<ScrollArea h="100%" w="100%" aria-label={t("worldClock.advancedLabel")}>
|
||||
<Stack gap="md" p={{ base: "sm", sm: "md" }}>
|
||||
{primaryTimeZoneInvalid && (
|
||||
<Alert icon={<IconAlertTriangle />} color="yellow" title={t("worldClock.unsupportedPrimaryTitle")}>
|
||||
@@ -102,7 +103,7 @@ const PrimaryClock = ({ now, options, primary }: Pick<ModeProps, "now" | "option
|
||||
<Group justify="space-between" align="flex-start" gap="lg" wrap="wrap">
|
||||
<Stack gap={5} miw={0}>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThemeIcon color={getPhaseColor(primary.phase)} variant="light" radius="xl" size="md">
|
||||
<ThemeIcon color={getTimeOfDayPhaseColor(primary.phase)} variant="light" radius="xl" size="md">
|
||||
<IconClock style={iconSizes.md} />
|
||||
</ThemeIcon>
|
||||
<Title order={2} size="h4" fw={600}>
|
||||
@@ -321,10 +322,3 @@ const getPrimaryLabel = (options: ModeProps["options"], t: ScopedClockTranslator
|
||||
if (options.useCustomTimezone) return humanizeTimeZone(options.timezone);
|
||||
return t("worldClock.local");
|
||||
};
|
||||
|
||||
const getPhaseColor = (phase: TimeOfDayPhase) => {
|
||||
if (phase === "night") return "indigo";
|
||||
if (phase === "dawn") return "orange";
|
||||
if (phase === "day") return "cyan";
|
||||
return "grape";
|
||||
};
|
||||
@@ -1,5 +1,14 @@
|
||||
import type { TimeOfDayPhase } from "./world-clock";
|
||||
|
||||
export const automaticTimeFormat = "automatic";
|
||||
|
||||
export const getTimeOfDayPhaseColor = (phase: TimeOfDayPhase) => {
|
||||
if (phase === "night") return "indigo";
|
||||
if (phase === "dawn") return "orange";
|
||||
if (phase === "day") return "cyan";
|
||||
return "grape";
|
||||
};
|
||||
|
||||
export const resolveClockTimeFormat = (format: string, legacyIs24HourFormat: boolean) => {
|
||||
if (format && format !== automaticTimeFormat) return format;
|
||||
if (legacyIs24HourFormat) return "HH:mm";
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Badge, Box, Group, Progress, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { getTimeOfDayPhaseColor } from "./format";
|
||||
import type { TimeOfDayPhase } from "./world-clock";
|
||||
|
||||
interface TimeOfDayBarProps {
|
||||
@@ -45,7 +46,7 @@ export const TimeOfDayBar = ({
|
||||
return (
|
||||
<Stack component="figure" gap={6} m={0} aria-label={label}>
|
||||
<Group justify="space-between" align="center" gap="xs" wrap="nowrap">
|
||||
<Badge color={getPhaseColor(phase)} variant="dot" size="sm">
|
||||
<Badge color={getTimeOfDayPhaseColor(phase)} variant="dot" size="sm">
|
||||
{t(`worldClock.phase.${phase}`)}
|
||||
</Badge>
|
||||
<Text size="xs" c="dimmed" ta="right">
|
||||
@@ -99,10 +100,3 @@ export const TimeOfDayBar = ({
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const getPhaseColor = (phase: TimeOfDayPhase) => {
|
||||
if (phase === "night") return "indigo";
|
||||
if (phase === "dawn") return "orange";
|
||||
if (phase === "day") return "cyan";
|
||||
return "grape";
|
||||
};
|
||||
@@ -4,6 +4,8 @@ import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import type { DataTableColumn } from "mantine-datatable";
|
||||
import { useDataTableColumns } from "mantine-datatable";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
interface TableLayoutOptions extends Record<string, unknown> {
|
||||
columnOrder?: string;
|
||||
columnWidths?: string;
|
||||
@@ -93,7 +95,7 @@ export const parseColumnWidths = (value: string, columnAccessors: readonly strin
|
||||
if (!value) return {};
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
||||
if (!isRecord(parsed)) return {};
|
||||
|
||||
const allowed = new Set(columnAccessors);
|
||||
return Object.fromEntries(
|
||||
@@ -107,7 +109,7 @@ export const parseColumnWidths = (value: string, columnAccessors: readonly strin
|
||||
}
|
||||
};
|
||||
|
||||
export const usePersistedTableLayout = <T,>({
|
||||
export const usePersistedTableLayout = <T>({
|
||||
columns,
|
||||
columnAccessors,
|
||||
columnOrder,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import type { CustomJsxRendererMessages, CustomWidgetPublishedQueryState } from "@homarr/custom-widgets/runtime";
|
||||
import { CustomJsxRenderer, parseRequestCapabilities } from "@homarr/custom-widgets/runtime";
|
||||
@@ -118,7 +119,3 @@ function sameStatus(left: CustomWidgetPublishedQueryState["status"], right: Cust
|
||||
left.error === right.error
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { QueryClient, QueryKey } from "@tanstack/react-query";
|
||||
import { hashKey } from "@tanstack/react-query";
|
||||
import type { DefaultErrorData } from "@trpc/server/unstable-core-do-not-import";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
import type { ServerSettings } from "@homarr/server-settings";
|
||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
@@ -163,9 +164,6 @@ export const widgetQueryInputMatches = (input: unknown, expected: Record<string,
|
||||
|
||||
export const widgetQueryValueEquals = (left: unknown, right: unknown) => hashKey([left]) === hashKey([right]);
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
|
||||
export interface WidgetProps<TKind extends WidgetKind> {
|
||||
options: inferOptionsFromCreator<WidgetOptionsRecordOf<TKind>>;
|
||||
integrationIds: string[];
|
||||
|
||||
@@ -36,12 +36,13 @@ import { invariantTechnicalLabels } from "@homarr/definitions";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { constructBoardPermissions } from "@homarr/auth/shared";
|
||||
import { useOptionalBoard } from "@homarr/boards/context";
|
||||
import { formatBytes, useTimeAgo } from "@homarr/common";
|
||||
import { useTimeAgo } from "@homarr/common";
|
||||
import type { ContainerState, DockerEndpointCapability } from "@homarr/docker";
|
||||
import { containerStateColorMap, cpuUsageColor, memoryUsageColor, safeValue } from "@homarr/docker/shared";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { AddDockerAppToHomarr, useDockerContainerRemovalConfirmation } from "@homarr/modals-collection";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
@@ -115,6 +116,7 @@ const createColumns = (
|
||||
tCommon: ReturnType<typeof useI18n<"common">>,
|
||||
handlers: ContainerActionHandlers,
|
||||
sortingEnabled: boolean,
|
||||
formatBytes: (bytes: number) => string,
|
||||
): DataTableColumn<DockerContainer>[] => [
|
||||
{
|
||||
accessor: "name",
|
||||
@@ -253,6 +255,7 @@ export default function DockerWidget({
|
||||
const confirmRemoval = useDockerContainerRemovalConfirmation();
|
||||
const board = useOptionalBoard();
|
||||
const { data: session } = useSession();
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const hasChangeAccess = board ? constructBoardPermissions(board, session).hasChangeAccess : false;
|
||||
const isAdvanced = displayMode === "advanced";
|
||||
|
||||
@@ -365,10 +368,10 @@ export default function DockerWidget({
|
||||
);
|
||||
const columns = useMemo(() => {
|
||||
const sortingEnabled = (isAdvanced || options.enableRowSorting) && !isEditMode;
|
||||
return createColumns(t, tCommon, actionHandlers, sortingEnabled).filter(
|
||||
return createColumns(t, tCommon, actionHandlers, sortingEnabled, formatBytes).filter(
|
||||
({ accessor }) => columnVisibility[String(accessor) as keyof typeof columnVisibility],
|
||||
);
|
||||
}, [actionHandlers, columnVisibility, isAdvanced, isEditMode, options.enableRowSorting, t, tCommon]);
|
||||
}, [actionHandlers, columnVisibility, formatBytes, isAdvanced, isEditMode, options.enableRowSorting, t, tCommon]);
|
||||
const { effectiveColumns, storeKey } = usePersistedTableLayout({
|
||||
columns,
|
||||
columnAccessors,
|
||||
|
||||
@@ -46,10 +46,11 @@ import { clientApi } from "@homarr/api/client";
|
||||
import { useIntegrationsWithInteractAccess, useSession } from "@homarr/auth/client";
|
||||
import { constructBoardPermissions } from "@homarr/auth/shared";
|
||||
import { useOptionalBoard } from "@homarr/boards/context";
|
||||
import { formatByteRate, formatBytes, useIntegrationConnected } from "@homarr/common";
|
||||
import { useIntegrationConnected } from "@homarr/common";
|
||||
import { getIconUrl, getIntegrationKindsByCategory } from "@homarr/definitions";
|
||||
import type { ExtendedClientStatus, ExtendedDownloadClientItem } from "@homarr/integrations";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
@@ -200,6 +201,15 @@ function formatRatio(ratio: number): string {
|
||||
return ratio.toFixed(2);
|
||||
}
|
||||
|
||||
function formatSizePair(
|
||||
used: number,
|
||||
total: number,
|
||||
formatBytesPair: (used: number, total: number) => { used: string; total: string },
|
||||
): string {
|
||||
const formatted = formatBytesPair(used, total);
|
||||
return `${formatted.used} / ${formatted.total}`;
|
||||
}
|
||||
|
||||
function showCompletedItem(
|
||||
item: Pick<ExtendedDownloadClientItem, "type" | "progress" | "upSpeed">,
|
||||
options: WidgetComponentProps<"downloads">["options"],
|
||||
@@ -252,8 +262,12 @@ function compareSortValues(
|
||||
return 0;
|
||||
}
|
||||
|
||||
function buildProgressTooltip(record: ExtendedDownloadClientItem): string {
|
||||
const parts = [`${formatBytes(record.received)} / ${formatBytes(record.size)}`];
|
||||
function buildProgressTooltip(
|
||||
record: ExtendedDownloadClientItem,
|
||||
formatBytesPair: (used: number, total: number) => { used: string; total: string },
|
||||
formatByteRate: (bytes: number) => string,
|
||||
): string {
|
||||
const parts = [formatSizePair(record.received, record.size, formatBytesPair)];
|
||||
if (record.downSpeed) parts.push(`↓ ${formatByteRate(record.downSpeed)}`);
|
||||
if (record.time !== 0) parts.push(`ETA: ${dayjs().add(record.time, "milliseconds").fromNow(true)}`);
|
||||
return parts.join(" · ");
|
||||
@@ -268,6 +282,7 @@ function SpeedCell({
|
||||
fontSize: SizeConfig["fontSize"];
|
||||
direction: keyof typeof speedColumnConfig;
|
||||
}) {
|
||||
const { formatByteRate } = useByteFormatter();
|
||||
if (!speed) return null;
|
||||
const { Icon, color } = speedColumnConfig[direction];
|
||||
return (
|
||||
@@ -291,6 +306,7 @@ export default function DownloadClientsWidget({
|
||||
height,
|
||||
displayMode,
|
||||
}: WidgetComponentProps<"downloads">) {
|
||||
const { formatByteRate, formatBytes, formatBytesPair } = useByteFormatter();
|
||||
const board = useOptionalBoard();
|
||||
const { data: session } = useSession();
|
||||
const hasChangeAccess = board ? constructBoardPermissions(board, session).hasChangeAccess : false;
|
||||
@@ -497,7 +513,7 @@ export default function DownloadClientsWidget({
|
||||
render: (record) => (
|
||||
<Tooltip
|
||||
key={displayMode}
|
||||
label={buildHoverTooltip(record, t)}
|
||||
label={buildHoverTooltip(record, t, formatBytesPair, formatByteRate)}
|
||||
multiline
|
||||
w={280}
|
||||
withArrow
|
||||
@@ -533,7 +549,7 @@ export default function DownloadClientsWidget({
|
||||
return (
|
||||
<Tooltip
|
||||
key={displayMode}
|
||||
label={buildProgressTooltip(record)}
|
||||
label={buildProgressTooltip(record, formatBytesPair, formatByteRate)}
|
||||
withArrow
|
||||
openDelay={300}
|
||||
position="top"
|
||||
@@ -679,7 +695,7 @@ export default function DownloadClientsWidget({
|
||||
},
|
||||
];
|
||||
return cols.filter(Boolean) as DataTableColumn<ExtendedDownloadClientItem>[];
|
||||
}, [columnContext, t, size, progressColumnWidth, displayMode]);
|
||||
}, [columnContext, displayMode, formatByteRate, formatBytes, formatBytesPair, progressColumnWidth, size, t]);
|
||||
|
||||
const { effectiveColumns, storeKey } = usePersistedTableLayout({
|
||||
columns,
|
||||
@@ -818,9 +834,14 @@ export default function DownloadClientsWidget({
|
||||
);
|
||||
}
|
||||
|
||||
function buildHoverTooltip(record: ExtendedDownloadClientItem, t: DownloadsT): React.ReactNode {
|
||||
function buildHoverTooltip(
|
||||
record: ExtendedDownloadClientItem,
|
||||
t: DownloadsT,
|
||||
formatBytesPair: (used: number, total: number) => { used: string; total: string },
|
||||
formatByteRate: (bytes: number) => string,
|
||||
): React.ReactNode {
|
||||
const lines: { label: string; value: string }[] = [
|
||||
{ label: t("items.size.detailsTitle"), value: `${formatBytes(record.received)} / ${formatBytes(record.size)}` },
|
||||
{ label: t("items.size.detailsTitle"), value: formatSizePair(record.received, record.size, formatBytesPair) },
|
||||
{ label: t("items.state.detailsTitle"), value: t(`states.${record.state}`) },
|
||||
];
|
||||
|
||||
@@ -864,6 +885,7 @@ function buildHoverTooltip(record: ExtendedDownloadClientItem, t: DownloadsT): R
|
||||
function ExpandedRow({ item, collapse }: { item: ExtendedDownloadClientItem; collapse: () => void }) {
|
||||
const t = useI18n("widget.downloads");
|
||||
const locale = useCurrentIntlLocale();
|
||||
const { formatByteRate, formatBytes, formatBytesPair } = useByteFormatter();
|
||||
const progressPercent = Math.floor(item.progress * 100);
|
||||
const categoryDisplay = formatCategoryDisplay(item.category);
|
||||
|
||||
@@ -900,7 +922,7 @@ function ExpandedRow({ item, collapse }: { item: ExtendedDownloadClientItem; col
|
||||
<SimpleGrid cols={3} spacing="xs" verticalSpacing={4} style={{ minWidth: 0 }}>
|
||||
<DetailPair
|
||||
label={t("items.size.detailsTitle")}
|
||||
value={`${formatBytes(item.received)} / ${formatBytes(item.size)}`}
|
||||
value={formatSizePair(item.received, item.size, formatBytesPair)}
|
||||
/>
|
||||
{item.downSpeed !== undefined && item.downSpeed > 0 && (
|
||||
<DetailPair
|
||||
@@ -979,6 +1001,7 @@ function GlobalStatsBar({
|
||||
clients: ExtendedClientStatus[];
|
||||
}) {
|
||||
const t = useI18n("widget.downloads");
|
||||
const { formatByteRate, formatBytesPair } = useByteFormatter();
|
||||
|
||||
let overallProgress = 0;
|
||||
if (queueStats.totalSize > 0) overallProgress = queueStats.completedSize / queueStats.totalSize;
|
||||
@@ -998,7 +1021,7 @@ function GlobalStatsBar({
|
||||
<Tooltip label={t("stats.totalSize")} withArrow>
|
||||
<Group gap={4}>
|
||||
<IconDatabase size="var(--mantine-font-size-xs)" style={{ opacity: 0.6 }} />
|
||||
<Text size="xs">{`${formatBytes(queueStats.completedSize)} / ${formatBytes(queueStats.totalSize)}`}</Text>
|
||||
<Text size="xs">{formatSizePair(queueStats.completedSize, queueStats.totalSize, formatBytesPair)}</Text>
|
||||
</Group>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
@@ -1199,6 +1222,7 @@ function WidgetFooter({
|
||||
toggleStats,
|
||||
}: WidgetFooterProps) {
|
||||
const t = useI18n("widget.downloads");
|
||||
const { formatByteRate } = useByteFormatter();
|
||||
const [filterOpen, { toggle: toggleFilter }] = useDisclosure(false);
|
||||
const someInteract = clients.some(({ interact }) => interact);
|
||||
const hasActiveFilter = clientFilter.length > 0 || statusFilter.length > 0;
|
||||
|
||||
@@ -66,6 +66,7 @@ export const { definition, componentLoader } = createWidgetDefinition("downloads
|
||||
validate: z.number().min(0),
|
||||
defaultValue: 0,
|
||||
step: 1,
|
||||
storedUnit: "kibibytesPerSecond",
|
||||
}),
|
||||
categoryFilter: factory.multiText({
|
||||
defaultValue: [] as string[],
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { calculateBandwidth, formatBitsPerSec } from "./bandwidth";
|
||||
import { formatBitRate } from "@homarr/common";
|
||||
|
||||
import { calculateBandwidth } from "./bandwidth";
|
||||
|
||||
describe("calculateBandwidth", () => {
|
||||
test("sorts samples before calculating a rate", () => {
|
||||
@@ -32,9 +34,9 @@ describe("calculateBandwidth", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatBitsPerSec", () => {
|
||||
describe("formatBitRate", () => {
|
||||
test("handles invalid and negative rates", () => {
|
||||
expect(formatBitsPerSec(Number.NaN, 2)).toBe("0 b/s");
|
||||
expect(formatBitsPerSec(-1, 2)).toBe("0 b/s");
|
||||
expect(formatBitRate(Number.NaN)).toBe("0 b/s");
|
||||
expect(formatBitRate(-1)).toBe("0 b/s");
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,5 @@
|
||||
import type { FirewallInterface, FirewallInterfacesSummary } from "@homarr/integrations";
|
||||
|
||||
export function formatBitsPerSec(bitsPerSecond: number, decimals: number): string {
|
||||
if (!Number.isFinite(bitsPerSecond) || bitsPerSecond <= 0) return "0 b/s";
|
||||
|
||||
const unitSize = 1024;
|
||||
const sizes = ["b/s", "kb/s", "Mb/s", "Gb/s", "Tb/s", "Pb/s", "Eb/s", "Zb/s", "Yb/s"];
|
||||
const unitIndex = Math.min(Math.floor(Math.log(bitsPerSecond) / Math.log(unitSize)), sizes.length - 1);
|
||||
|
||||
return `${parseFloat((bitsPerSecond / Math.pow(unitSize, unitIndex)).toFixed(decimals))} ${sizes[unitIndex]}`;
|
||||
}
|
||||
|
||||
export function calculateBandwidth(data: FirewallInterfacesSummary[]): { data: FirewallInterface[] } {
|
||||
const samples = data
|
||||
.filter((sample) => Number.isFinite(new Date(sample.timestamp).getTime()))
|
||||
|
||||
@@ -19,13 +19,14 @@ import { useLocalStorage } from "@mantine/hooks";
|
||||
import { IconArrowBarDown, IconArrowBarUp, IconBrain, IconCpu, IconTopologyBus } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatBitRate } from "@homarr/common";
|
||||
import { invariantTechnicalLabels } from "@homarr/definitions";
|
||||
import type { FirewallInterfacesSummary } from "@homarr/integrations";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { calculateBandwidth, formatBitsPerSec } from "./bandwidth";
|
||||
import { calculateBandwidth } from "./bandwidth";
|
||||
import { FirewallMenu } from "./firewall-menu";
|
||||
import { FirewallVersion, formatVersion } from "./firewall-version";
|
||||
import classes from "./firewall.module.css";
|
||||
@@ -409,7 +410,7 @@ const InterfacesPanel = ({
|
||||
color="light-dark(var(--mantine-color-green-8), var(--mantine-color-green-3))"
|
||||
/>
|
||||
<Text size="xs" c="light-dark(var(--mantine-color-green-8), var(--mantine-color-green-3))">
|
||||
{formatBitsPerSec(transmit, 2)}
|
||||
{formatBitRate(transmit)}
|
||||
</Text>
|
||||
</Group>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
@@ -418,7 +419,7 @@ const InterfacesPanel = ({
|
||||
color="light-dark(var(--mantine-color-yellow-9), var(--mantine-color-yellow-3))"
|
||||
/>
|
||||
<Text size="xs" c="light-dark(var(--mantine-color-yellow-9), var(--mantine-color-yellow-3))">
|
||||
{formatBitsPerSec(receive, 2)}
|
||||
{formatBitRate(receive)}
|
||||
</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
@@ -16,8 +16,9 @@ import {
|
||||
import dayjs from "dayjs";
|
||||
import duration from "dayjs/plugin/duration";
|
||||
|
||||
import { capitalize, formatBytes, formatBytesPair } from "@homarr/common";
|
||||
import { capitalize } from "@homarr/common";
|
||||
import type { ComputeResource, Resource, StorageResource } from "@homarr/integrations/types";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
@@ -94,6 +95,7 @@ const RightSection = ({ label, value }: RightSectionProps) => {
|
||||
|
||||
const ComputeResourceDetails = ({ item }: { item: ComputeResource }) => {
|
||||
const t = useI18n("widget.healthMonitoring.cluster.popover.detail");
|
||||
const { formatBytesPair } = useByteFormatter();
|
||||
const memory = formatBytesPair(item.memory.used, item.memory.total);
|
||||
const storage = formatBytesPair(item.storage.used, item.storage.total);
|
||||
return (
|
||||
@@ -102,10 +104,10 @@ const ComputeResourceDetails = ({ item }: { item: ComputeResource }) => {
|
||||
{t("cpu")} - {item.cpu.cores}
|
||||
</List.Item>
|
||||
<List.Item icon={<IconBrain size="var(--mantine-font-size-md)" />}>
|
||||
{t("memory")} - {memory.used} / {memory.available}
|
||||
{t("memory")} - {memory.used} / {memory.total}
|
||||
</List.Item>
|
||||
<List.Item icon={<IconDatabase size="var(--mantine-font-size-md)" />}>
|
||||
{t("storage")} - {storage.used} / {storage.available}
|
||||
{t("storage")} - {storage.used} / {storage.total}
|
||||
</List.Item>
|
||||
<List.Item icon={<IconClockHour3 size="var(--mantine-font-size-md)" />}>
|
||||
{t("uptime")} - {dayjs(dayjs().add(-item.uptime, "seconds")).fromNow(true)}
|
||||
@@ -123,6 +125,7 @@ const ComputeResourceDetails = ({ item }: { item: ComputeResource }) => {
|
||||
|
||||
const StorageResourceDetails = ({ item }: { item: StorageResource }) => {
|
||||
const t = useI18n("widget.healthMonitoring.cluster.popover.detail");
|
||||
const { formatBytesPair } = useByteFormatter();
|
||||
const storagePercent = item.total ? (item.used / item.total) * 100 : 0;
|
||||
const storage = formatBytesPair(item.used, item.total);
|
||||
return (
|
||||
@@ -137,7 +140,7 @@ const StorageResourceDetails = ({ item }: { item: StorageResource }) => {
|
||||
/>
|
||||
<Group align="center" gap={0}>
|
||||
<Text>
|
||||
{t("storage")} - {storage.used} / {storage.available}
|
||||
{t("storage")} - {storage.used} / {storage.total}
|
||||
</Text>
|
||||
</Group>
|
||||
</Center>
|
||||
@@ -149,6 +152,7 @@ const StorageResourceDetails = ({ item }: { item: StorageResource }) => {
|
||||
};
|
||||
|
||||
const DiskStats = ({ item }: { item: ComputeResource }) => {
|
||||
const { formatBytes } = useByteFormatter();
|
||||
if (!item.storage.read || !item.storage.write) {
|
||||
return null;
|
||||
}
|
||||
@@ -169,6 +173,7 @@ const DiskStats = ({ item }: { item: ComputeResource }) => {
|
||||
};
|
||||
|
||||
const NetStats = ({ item }: { item: ComputeResource }) => {
|
||||
const { formatBytes } = useByteFormatter();
|
||||
if (!item.network.in || !item.network.out) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { GaugeChart } from "@mantine/charts";
|
||||
import { Center, Text, Tooltip } from "@mantine/core";
|
||||
import { IconBrain } from "@tabler/icons-react";
|
||||
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
import { progressColor } from "../system-health";
|
||||
@@ -17,7 +18,8 @@ export const MemoryRing = ({
|
||||
isTiny: boolean;
|
||||
ariaLabel: string;
|
||||
}) => {
|
||||
const memoryUsage = formatMemoryUsage(available, used);
|
||||
const { formatBytes, formatBytesPair } = useByteFormatter();
|
||||
const memoryUsage = formatMemoryUsage(available, used, formatBytes, formatBytesPair);
|
||||
|
||||
return (
|
||||
<Tooltip label={`${memoryUsage.memUsed.percent}%`}>
|
||||
@@ -35,7 +37,7 @@ export const MemoryRing = ({
|
||||
label={
|
||||
<Center style={{ flexDirection: "column" }}>
|
||||
<Text className="health-monitoring-memory-value" size={isTiny ? "8px" : "xs"}>
|
||||
{memoryUsage.memUsed.GB}GiB
|
||||
{memoryUsage.memUsed.formatted}
|
||||
</Text>
|
||||
<IconBrain className="health-monitoring-memory-icon" style={zoomCompensatedSize(isTiny ? 8 : 16)} />
|
||||
</Center>
|
||||
@@ -45,17 +47,20 @@ export const MemoryRing = ({
|
||||
);
|
||||
};
|
||||
|
||||
export const formatMemoryUsage = (memFree: number, memUsed: number) => {
|
||||
export const formatMemoryUsage = (
|
||||
memFree: number,
|
||||
memUsed: number,
|
||||
formatBytes: (bytes: number) => string,
|
||||
formatBytesPair: (used: number, total: number) => { used: string; total: string },
|
||||
) => {
|
||||
const totalMemory = memFree + memUsed;
|
||||
const memFreeGB = (memFree / 1024 ** 3).toFixed(2);
|
||||
const memUsedGB = (memUsed / 1024 ** 3).toFixed(2);
|
||||
const memFreePercent = Math.round((memFree / totalMemory) * 100);
|
||||
const memUsedPercent = Math.round((memUsed / totalMemory) * 100);
|
||||
const memTotalGB = (totalMemory / 1024 ** 3).toFixed(2);
|
||||
const { used: formattedFree, total: formattedTotal } = formatBytesPair(memFree, totalMemory);
|
||||
|
||||
return {
|
||||
memFree: { percent: memFreePercent, GB: memFreeGB },
|
||||
memUsed: { percent: memUsedPercent, GB: memUsedGB },
|
||||
memTotal: { GB: memTotalGB },
|
||||
memFree: { percent: memFreePercent, formatted: formattedFree },
|
||||
memUsed: { percent: memUsedPercent, formatted: formatBytes(memUsed) },
|
||||
memTotal: { formatted: formattedTotal },
|
||||
};
|
||||
};
|
||||
@@ -37,7 +37,7 @@ import duration from "dayjs/plugin/duration";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import type { ScopedTranslationFunction } from "@homarr/translation";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
@@ -72,6 +72,7 @@ export const SystemHealthMonitoring = ({
|
||||
);
|
||||
const [openedIntegrationId, setOpenedIntegrationId] = useState<string | null>(null);
|
||||
const board = useRequiredBoard();
|
||||
const { formatBytes, formatBytesPair } = useByteFormatter();
|
||||
|
||||
const isAdvanced = displayMode === "advanced";
|
||||
const isTiny = !isAdvanced && width < 256;
|
||||
@@ -113,7 +114,12 @@ export const SystemHealthMonitoring = ({
|
||||
);
|
||||
const filteredSmart = filterStorageVolumes(healthInfo.smart, options.visibleStorageVolumes, integrationId);
|
||||
const disksData = matchFileSystemAndSmart(filteredFileSystem, filteredSmart);
|
||||
const memoryUsage = formatMemoryUsage(healthInfo.memAvailableInBytes, healthInfo.memUsedInBytes);
|
||||
const memoryUsage = formatMemoryUsage(
|
||||
healthInfo.memAvailableInBytes,
|
||||
healthInfo.memUsedInBytes,
|
||||
formatBytes,
|
||||
formatBytesPair,
|
||||
);
|
||||
const hasAttentionState = healthInfo.rebootRequired || healthInfo.availablePkgUpdates > 0;
|
||||
return (
|
||||
<Stack
|
||||
@@ -211,6 +217,7 @@ export const SystemHealthMonitoring = ({
|
||||
)}
|
||||
{showFileSystem &&
|
||||
disksData.map((disk) => {
|
||||
const sizes = formatFileSizePair(disk.used, disk.available, formatBytes, formatBytesPair);
|
||||
return (
|
||||
<Card
|
||||
className={combineClasses(
|
||||
@@ -267,10 +274,10 @@ export const SystemHealthMonitoring = ({
|
||||
</Progress.Root>
|
||||
<Group justify="space-between" gap={8} wrap="nowrap">
|
||||
<Text className="health-monitoring-disk-use-value" size="xs" c="dimmed">
|
||||
{t("popover.used")} {formatFileSize(disk.used)}
|
||||
{t("popover.used")} {sizes.used}
|
||||
</Text>
|
||||
<Text className="health-monitoring-disk-available-value" size="xs" c="dimmed">
|
||||
{formatFileSize(disk.available)} {t("popover.available")}
|
||||
{sizes.available} {t("popover.available")}
|
||||
</Text>
|
||||
</Group>
|
||||
</Stack>
|
||||
@@ -322,14 +329,14 @@ const SystemInformationList = ({
|
||||
className="health-monitoring-information-memory"
|
||||
icon={<IconBrain size={iconSizeProp} style={iconStyle} />}
|
||||
>
|
||||
{t("popover.memory", { memory: memoryUsage.memTotal.GB })}
|
||||
{t("popover.memory", { memory: memoryUsage.memTotal.formatted })}
|
||||
</List.Item>
|
||||
<List.Item
|
||||
className="health-monitoring-information-memory"
|
||||
icon={<IconBrain size={iconSizeProp} style={iconStyle} />}
|
||||
>
|
||||
{t("popover.memoryAvailable", {
|
||||
memoryAvailable: memoryUsage.memFree.GB,
|
||||
memoryAvailable: memoryUsage.memFree.formatted,
|
||||
percent: String(memoryUsage.memFree.percent),
|
||||
})}
|
||||
</List.Item>
|
||||
@@ -394,11 +401,33 @@ export const progressColor = (percentage: number) => {
|
||||
|
||||
// Some integrations report file sizes as raw bytes (e.g. TrueNAS, Glances) while others pre-format
|
||||
// them (e.g. Unraid, dashdot). Format the former and pass the latter through untouched.
|
||||
const formatFileSize = (value: string) => {
|
||||
const formatFileSize = (value: string, formatBytes: (bytes: number) => string) => {
|
||||
const bytes = Number(value);
|
||||
return Number.isFinite(bytes) ? formatBytes(Math.round(bytes)) : value;
|
||||
};
|
||||
|
||||
const formatFileSizePair = (
|
||||
usedValue: string,
|
||||
availableValue: string,
|
||||
formatBytes: (bytes: number) => string,
|
||||
formatBytesPair: (used: number, total: number) => { used: string; total: string },
|
||||
) => {
|
||||
const used = Number(usedValue);
|
||||
const available = Number(availableValue);
|
||||
if (!Number.isFinite(used) || !Number.isFinite(available)) {
|
||||
return {
|
||||
used: formatFileSize(usedValue, formatBytes),
|
||||
available: formatFileSize(availableValue, formatBytes),
|
||||
};
|
||||
}
|
||||
|
||||
const total = Math.round(used + available);
|
||||
return {
|
||||
used: formatBytesPair(Math.round(used), total).used,
|
||||
available: formatBytesPair(Math.round(available), total).used,
|
||||
};
|
||||
};
|
||||
|
||||
interface FileSystem {
|
||||
deviceName: string;
|
||||
used: string;
|
||||
|
||||
@@ -36,6 +36,10 @@ vi.mock("@homarr/translation/client", () => ({
|
||||
useI18n: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/settings", () => ({
|
||||
useByteFormatter: () => ({ formatBytes: (bytes: number) => `${bytes} B` }),
|
||||
}));
|
||||
|
||||
describe("Immich album queries", () => {
|
||||
let host: HTMLDivElement | undefined;
|
||||
let root: ReturnType<typeof createRoot> | undefined;
|
||||
|
||||
@@ -6,8 +6,8 @@ import { IconDatabase, IconPhoto, IconUsers, IconVideo } from "@tabler/icons-rea
|
||||
import { getQueryKey } from "@trpc/react-query";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
import { WidgetEmptyState } from "../../common/empty-state";
|
||||
@@ -28,6 +28,7 @@ export default function ImmichServerStatsWidget({
|
||||
widgetRuntimeRef,
|
||||
}: WidgetComponentProps<"immich-serverStats">) {
|
||||
const t = useI18n("widget.immich-serverStats");
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const locale = useCurrentIntlLocale();
|
||||
const input = { integrationId: integrationIds[0] ?? "" };
|
||||
const albumsInput = { ...input, limit: MAX_ADVANCED_ALBUMS };
|
||||
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { objectEntries } from "@homarr/common";
|
||||
import { formatBitRate, objectEntries } from "@homarr/common";
|
||||
import { getIconUrl } from "@homarr/definitions";
|
||||
import type { StreamSession } from "@homarr/integrations";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
@@ -74,7 +74,7 @@ const playbackStatusColorMap = {
|
||||
|
||||
function formatBitrate(bitrateKbps: number | null | undefined): string | null {
|
||||
if (!bitrateKbps || bitrateKbps <= 0) return null;
|
||||
return bitrateKbps >= 1000 ? `${(bitrateKbps / 1000).toFixed(1)} Mbps` : `${Math.round(bitrateKbps)} kbps`;
|
||||
return formatBitRate(bitrateKbps * 1000);
|
||||
}
|
||||
|
||||
const RESOLUTION_TIER_HEIGHTS = [4320, 2160, 1440, 1080, 720, 480, 360, 240] as const;
|
||||
|
||||
@@ -14,8 +14,8 @@ import {
|
||||
} from "@mantine/core";
|
||||
import { IconHeartbeat, IconTransform } from "@tabler/icons-react";
|
||||
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import type { TdarrQueue } from "@homarr/integrations";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
interface QueuePanelProps {
|
||||
@@ -24,6 +24,7 @@ interface QueuePanelProps {
|
||||
|
||||
export function QueuePanel(props: QueuePanelProps) {
|
||||
const { queue } = props;
|
||||
const { formatBytes } = useByteFormatter();
|
||||
|
||||
const t = useI18n("widget.mediaTranscoding.panel.queue");
|
||||
const tCommon = useI18n("widget.mediaTranscoding.panel.common");
|
||||
|
||||
@@ -3,8 +3,8 @@ import { Card, Center, Group, RingProgress, ScrollArea, Stack, Text, Title, Tool
|
||||
import { IconDatabaseHeart, IconFileDescription, IconHeartbeat, IconTransform } from "@tabler/icons-react";
|
||||
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import type { TdarrPieSegment, TdarrStatistics } from "@homarr/integrations";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import type { TablerIcon } from "@homarr/ui";
|
||||
|
||||
@@ -17,6 +17,7 @@ interface StatisticsPanelProps {
|
||||
export function StatisticsPanel(props: StatisticsPanelProps) {
|
||||
const t = useI18n("widget.mediaTranscoding.panel.statistics");
|
||||
const tCommon = useI18n("widget.mediaTranscoding.panel.common");
|
||||
const { formatBytes } = useByteFormatter();
|
||||
|
||||
const allLibs = props.statistics;
|
||||
|
||||
|
||||
@@ -104,6 +104,7 @@ interface IntegrationMultiSelectInput extends CommonInput<string[]> {
|
||||
interface NumberInput extends CommonInput<number> {
|
||||
validate: z.ZodNumber;
|
||||
step?: number;
|
||||
storedUnit?: "kibibytesPerSecond";
|
||||
}
|
||||
|
||||
interface SliderInput extends CommonInput<number> {
|
||||
@@ -201,6 +202,7 @@ const optionsFactory = {
|
||||
type: "number" as const,
|
||||
defaultValue: input.defaultValue ?? 0,
|
||||
step: input.step,
|
||||
storedUnit: input.storedUnit,
|
||||
withDescription: input.withDescription ?? false,
|
||||
validate: input.validate,
|
||||
}),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { formatNumber } from "@homarr/common";
|
||||
import { formatBitRate } from "@homarr/common";
|
||||
import type {
|
||||
SpeedtestTrackerDashboardData,
|
||||
SpeedtestTrackerResult,
|
||||
@@ -80,17 +80,15 @@ export const combineSpeedtestDashboards = (
|
||||
{ latestResult: null, stats: null, recentResults: [] },
|
||||
);
|
||||
|
||||
export const formatBitsPerSec = (bps: number): string => `${formatNumber(bps, 2)}bps`;
|
||||
|
||||
export const formatResultSpeed = (result: SpeedtestTrackerResult, dir: "download" | "upload"): string => {
|
||||
const bits = dir === "download" ? result.download_bits : result.upload_bits;
|
||||
if (bits != null) return formatBitsPerSec(bits);
|
||||
if (bits != null) return formatBitRate(bits);
|
||||
return "—";
|
||||
};
|
||||
|
||||
export const formatStatsSpeed = (band: SpeedtestTrackerStats["download"]): string => {
|
||||
if (band.avg_bits != null) return formatBitsPerSec(band.avg_bits);
|
||||
return formatBitsPerSec(band.avg * 8);
|
||||
if (band.avg_bits != null) return formatBitRate(band.avg_bits);
|
||||
return formatBitRate(band.avg * 8);
|
||||
};
|
||||
|
||||
type CompactSection = "latest" | "chart" | "averages";
|
||||
|
||||
@@ -7,11 +7,14 @@ import { useElementSize } from "@mantine/hooks";
|
||||
import { XAxis } from "recharts";
|
||||
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { formatBitRate } from "@homarr/common";
|
||||
import type { SpeedtestTrackerResult } from "@homarr/integrations/types";
|
||||
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { SectionLabel } from "./section-label";
|
||||
|
||||
const formatChartBitRate = (value: number) => formatBitRate(value);
|
||||
|
||||
interface XAxisTicks {
|
||||
midnightTs: number | null;
|
||||
xTicks: number[];
|
||||
@@ -182,11 +185,8 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
|
||||
.filter((result) => (result.download_bits ?? 0) > 0)
|
||||
.map((result) => ({
|
||||
ts: result.created_at.getTime(),
|
||||
Download: parseFloat(((result.download_bits ?? 0) / 1_000_000).toFixed(2)),
|
||||
Upload:
|
||||
result.upload_bits != null && result.upload_bits > 0
|
||||
? parseFloat((result.upload_bits / 1_000_000).toFixed(2))
|
||||
: 0,
|
||||
Download: result.download_bits ?? 0,
|
||||
Upload: result.upload_bits != null && result.upload_bits > 0 ? result.upload_bits : 0,
|
||||
})),
|
||||
[results],
|
||||
);
|
||||
@@ -194,8 +194,8 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
|
||||
const yConfig = useMemo(
|
||||
() =>
|
||||
buildYAxisConfig(Math.max(...data.map((item) => Math.max(item.Download, item.Upload)), 0), [
|
||||
{ threshold: 400, step: 100 },
|
||||
{ threshold: Infinity, step: 200 },
|
||||
{ threshold: 400_000_000, step: 100_000_000 },
|
||||
{ threshold: Infinity, step: 200_000_000 },
|
||||
]),
|
||||
[data],
|
||||
);
|
||||
@@ -221,7 +221,7 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
|
||||
withLegend
|
||||
fillOpacity={0.2}
|
||||
styles={{ root: { padding: 5, borderRadius: theme.radius[board.itemRadius] } }}
|
||||
valueFormatter={(val: number) => `${val} Mbps`}
|
||||
valueFormatter={formatChartBitRate}
|
||||
xAxisProps={{
|
||||
type: "number",
|
||||
domain: ["dataMin", "dataMax"],
|
||||
@@ -233,8 +233,8 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
|
||||
yAxisProps={{
|
||||
ticks: yConfig.ticks,
|
||||
domain: yConfig.domain,
|
||||
tickFormatter: (val: number) => `${val}`,
|
||||
width: 50,
|
||||
tickFormatter: formatChartBitRate,
|
||||
width: 70,
|
||||
tick: { fontSize: 10 },
|
||||
}}
|
||||
referenceLines={xTicks.map((tickTs) => ({
|
||||
@@ -257,7 +257,7 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
|
||||
<ChartTooltip
|
||||
label={formatTooltipDate(label, locale)}
|
||||
payload={payload}
|
||||
valueFormatter={(val: number) => `${val} Mbps`}
|
||||
valueFormatter={formatChartBitRate}
|
||||
/>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -5,7 +5,8 @@ import { Box, Card, Group, ScrollArea, SimpleGrid, Text, Tooltip, useComputedCol
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { formatBytesPair } from "@homarr/common";
|
||||
import { formatBytesPair as formatBytesPairDefault } from "@homarr/common";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { WidgetEmptyState } from "../common/empty-state";
|
||||
@@ -52,6 +53,7 @@ export const getDisplayText = (
|
||||
item: { used: string; available: string; percentage: number },
|
||||
displayMode: DiskDisplayMode,
|
||||
translatedFreeText?: string,
|
||||
formatBytesPair: typeof formatBytesPairDefault = formatBytesPairDefault,
|
||||
) => {
|
||||
switch (displayMode) {
|
||||
case "percentage":
|
||||
@@ -60,7 +62,7 @@ export const getDisplayText = (
|
||||
const usedInBytes = Number(item.used);
|
||||
const availableInBytes = Number(item.available);
|
||||
if (Number.isFinite(usedInBytes) && Number.isFinite(availableInBytes)) {
|
||||
const { used, available: total } = formatBytesPair(usedInBytes, usedInBytes + availableInBytes);
|
||||
const { used, total } = formatBytesPair(usedInBytes, usedInBytes + availableInBytes);
|
||||
return `${used} / ${total}`;
|
||||
}
|
||||
return `${item.used} / ${item.available}`;
|
||||
@@ -75,9 +77,10 @@ export const getDisplayText = (
|
||||
export const getAdvancedDisplayTexts = (
|
||||
item: { used: string; available: string; percentage: number },
|
||||
translatedFreeText?: string,
|
||||
formatBytesPair: typeof formatBytesPairDefault = formatBytesPairDefault,
|
||||
) => ({
|
||||
percentage: getDisplayText(item, "percentage"),
|
||||
absolute: getDisplayText(item, "absolute"),
|
||||
absolute: getDisplayText(item, "absolute", undefined, formatBytesPair),
|
||||
free: getDisplayText(item, "free", translatedFreeText),
|
||||
});
|
||||
|
||||
@@ -234,6 +237,7 @@ export default function SystemResources({
|
||||
displayMode,
|
||||
}: WidgetComponentProps<"systemDisks">) {
|
||||
const t = useI18n("widget.systemDisks");
|
||||
const { formatBytesPair } = useByteFormatter();
|
||||
const queryInput = { integrationIds };
|
||||
const healthQuery = clientApi.widget.healthMonitoring.getSystemHealthStatus.useQuery(queryInput);
|
||||
const results = getUsableWidgetQueryData(healthQuery) ?? [];
|
||||
@@ -294,7 +298,7 @@ export default function SystemResources({
|
||||
const freeText = t("status.free", {
|
||||
percentage: String(Math.round(100 - clampPercentage(item.percentage))),
|
||||
});
|
||||
const advancedDisplayTexts = getAdvancedDisplayTexts(item, freeText);
|
||||
const advancedDisplayTexts = getAdvancedDisplayTexts(item, freeText, formatBytesPair);
|
||||
|
||||
return (
|
||||
<SystemDiskCard
|
||||
@@ -302,7 +306,9 @@ export default function SystemResources({
|
||||
deviceName={item.deviceName}
|
||||
percentage={item.percentage}
|
||||
displayText={
|
||||
isAdvanced ? advancedDisplayTexts.percentage : getDisplayText(item, options.displayMode, freeText)
|
||||
isAdvanced
|
||||
? advancedDisplayTexts.percentage
|
||||
: getDisplayText(item, options.displayMode, freeText, formatBytesPair)
|
||||
}
|
||||
temperature={isAdvanced || options.showTemperatureIfAvailable ? smartItem?.temperature : undefined}
|
||||
healthy={smartItem?.healthy ?? true} // fall back to healthy if no information is available
|
||||
|
||||
@@ -17,7 +17,7 @@ describe("system disk display", () => {
|
||||
getAdvancedDisplayTexts({ used: `${5 * 1024 ** 3}`, available: `${5 * 1024 ** 3}`, percentage: 50 }),
|
||||
).toEqual({
|
||||
percentage: "50%",
|
||||
absolute: "5.0 GiB / 10.0 GiB",
|
||||
absolute: "5.4 GB / 10.7 GB",
|
||||
free: "50% free",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Box, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconNetwork } from "@tabler/icons-react";
|
||||
|
||||
import { formatByteRate } from "@homarr/common";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { LabelDisplayModeOption } from "..";
|
||||
@@ -27,29 +27,20 @@ export const CombinedNetworkTrafficChart = ({
|
||||
down: usage.down,
|
||||
}));
|
||||
const t = useI18n("widget.systemResources.card");
|
||||
const { formatByteRate } = useByteFormatter();
|
||||
|
||||
const tooltipLabel = (index: number) => {
|
||||
const point = usageOverTime[index];
|
||||
return (
|
||||
<Stack gap={2}>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Box
|
||||
bg="orange.5"
|
||||
w={8}
|
||||
h={8}
|
||||
style={{ borderRadius: 99, flexShrink: 0 }}
|
||||
/>
|
||||
<Box bg="orange.5" w={8} h={8} style={{ borderRadius: 99, flexShrink: 0 }} />
|
||||
<Text size="xs">
|
||||
{t("up")}: {formatByteRate(Math.round(point?.up ?? 0))}
|
||||
</Text>
|
||||
</Group>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Box
|
||||
bg="yellow.5"
|
||||
w={8}
|
||||
h={8}
|
||||
style={{ borderRadius: 99, flexShrink: 0 }}
|
||||
/>
|
||||
<Box bg="yellow.5" w={8} h={8} style={{ borderRadius: 99, flexShrink: 0 }} />
|
||||
<Text size="xs">
|
||||
{t("down")}: {formatByteRate(Math.round(point?.down ?? 0))}
|
||||
</Text>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { IconBrain } from "@tabler/icons-react";
|
||||
|
||||
import { formatBytesPair } from "@homarr/common";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { LabelDisplayModeOption } from "..";
|
||||
@@ -24,24 +24,21 @@ export const SystemResourceMemoryChart = ({
|
||||
usage,
|
||||
}));
|
||||
const t = useI18n("widget.systemResources.card");
|
||||
const { formatBytesPair } = useByteFormatter();
|
||||
|
||||
const percentageUsed =
|
||||
memoryUsageOverTime.length > 0 && totalCapacityInBytes > 0
|
||||
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
memoryUsageOverTime[memoryUsageOverTime.length - 1]! /
|
||||
totalCapacityInBytes
|
||||
memoryUsageOverTime[memoryUsageOverTime.length - 1]! / totalCapacityInBytes
|
||||
: undefined;
|
||||
|
||||
const tooltipLabel = (index: number) => {
|
||||
const used = memoryUsageOverTime[index] ?? 0;
|
||||
const memory = formatBytesPair(Math.round(used), totalCapacityInBytes);
|
||||
const percent =
|
||||
totalCapacityInBytes > 0
|
||||
? Math.round((used / totalCapacityInBytes) * 100)
|
||||
: 0;
|
||||
const percent = totalCapacityInBytes > 0 ? Math.round((used / totalCapacityInBytes) * 100) : 0;
|
||||
return t("memoryTooltip", {
|
||||
used: memory.used,
|
||||
available: memory.available,
|
||||
available: memory.total,
|
||||
percent,
|
||||
});
|
||||
};
|
||||
@@ -56,11 +53,7 @@ export const SystemResourceMemoryChart = ({
|
||||
labelDisplayMode={labelDisplayMode}
|
||||
advanced={advanced}
|
||||
yAxisProps={{ domain: [0, totalCapacityInBytes] }}
|
||||
lastValue={
|
||||
percentageUsed !== undefined
|
||||
? `${Math.round(percentageUsed * 100)}%`
|
||||
: undefined
|
||||
}
|
||||
lastValue={percentageUsed !== undefined ? `${Math.round(percentageUsed * 100)}%` : undefined}
|
||||
chartType={hasShadow ? "area" : "line"}
|
||||
tooltipLabel={tooltipLabel}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { IconArrowDown, IconArrowUp } from "@tabler/icons-react";
|
||||
|
||||
import { formatByteRate } from "@homarr/common";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { LabelDisplayModeOption } from "..";
|
||||
@@ -21,6 +21,7 @@ export const NetworkTrafficChart = ({
|
||||
}) => {
|
||||
const chartData = usageOverTime.map((usage, index) => ({ index, usage }));
|
||||
const t = useI18n("widget.systemResources.card");
|
||||
const { formatByteRate } = useByteFormatter();
|
||||
|
||||
const max = Math.max(...usageOverTime);
|
||||
const upperBound = max + max * 0.2;
|
||||
@@ -38,9 +39,7 @@ export const NetworkTrafficChart = ({
|
||||
chartType={hasShadow ? "area" : "line"}
|
||||
labelDisplayMode={labelDisplayMode}
|
||||
advanced={advanced}
|
||||
tooltipLabel={(index) =>
|
||||
formatByteRate(Math.round(usageOverTime[index] ?? 0))
|
||||
}
|
||||
tooltipLabel={(index) => formatByteRate(Math.round(usageOverTime[index] ?? 0))}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export type TimerMode = "timer" | "pomodoro";
|
||||
export type TimerPhase = "timer" | "focus" | "shortBreak" | "longBreak";
|
||||
export type TimerStatus = "idle" | "running" | "paused";
|
||||
@@ -281,7 +283,4 @@ const isTimerHistoryEntry = (value: unknown): value is TimerHistoryEntry => {
|
||||
return isFiniteNumber(value.completedAt) && isFiniteNumber(value.durationMs) && value.durationMs > 0;
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const isFiniteNumber = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);
|
||||
@@ -4,15 +4,15 @@ import { formatTotalTracearrBitrate, formatTracearrBitrate } from "./bitrate";
|
||||
|
||||
describe("Tracearr bitrate formatting", () => {
|
||||
test("sums raw Kbps before choosing the display unit", () => {
|
||||
expect(formatTotalTracearrBitrate([{ bitrate: 800 }, { bitrate: 1200 }])).toBe("2 Mbps");
|
||||
expect(formatTotalTracearrBitrate([{ bitrate: 800 }, { bitrate: 1200 }])).toBe("2 Mb/s");
|
||||
});
|
||||
|
||||
test("formats Gbps after aggregation", () => {
|
||||
expect(formatTotalTracearrBitrate([{ bitrate: 1_500_000 }, { bitrate: 500_000 }])).toBe("2 Gbps");
|
||||
test("formats Gb/s after aggregation", () => {
|
||||
expect(formatTotalTracearrBitrate([{ bitrate: 1_500_000 }, { bitrate: 500_000 }])).toBe("2 Gb/s");
|
||||
});
|
||||
|
||||
test("ignores missing and invalid bitrate values", () => {
|
||||
expect(formatTotalTracearrBitrate([{ bitrate: null }, { bitrate: Number.NaN }, { bitrate: 500 }])).toBe("500 kbps");
|
||||
expect(formatTotalTracearrBitrate([{ bitrate: null }, { bitrate: Number.NaN }, { bitrate: 500 }])).toBe("500 Kb/s");
|
||||
expect(formatTracearrBitrate(0)).toBe("—");
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,9 @@
|
||||
import type { TracearrStream } from "@homarr/integrations/types";
|
||||
import { formatBitRate } from "@homarr/common";
|
||||
|
||||
export function formatTracearrBitrate(kbps: number): string {
|
||||
if (!Number.isFinite(kbps) || kbps <= 0) return "—";
|
||||
if (kbps >= 1_000_000) return `${formatScaledBitrate(kbps / 1_000_000)} Gbps`;
|
||||
if (kbps >= 1000) return `${formatScaledBitrate(kbps / 1000)} Mbps`;
|
||||
return `${kbps} kbps`;
|
||||
return formatBitRate(kbps * 1000);
|
||||
}
|
||||
|
||||
export function formatTotalTracearrBitrate(streams: readonly Pick<TracearrStream, "bitrate">[]): string {
|
||||
@@ -14,7 +13,3 @@ export function formatTotalTracearrBitrate(streams: readonly Pick<TracearrStream
|
||||
}, 0);
|
||||
return formatTracearrBitrate(totalKbps);
|
||||
}
|
||||
|
||||
function formatScaledBitrate(value: number): string {
|
||||
return value % 1 === 0 ? value.toFixed(0) : value.toFixed(1);
|
||||
}
|
||||
Reference in new issue
Block a user