[优化] 添加度量工具函数和测试用例,优化仪表盘和趋势图组件

This commit is contained in:
ryan
2026-03-15 14:11:16 +08:00
parent 072930d55b
commit 25004fefae
5 changed files with 1178 additions and 1044 deletions
@@ -4,6 +4,8 @@ import { useMemo } from 'react';
import type { EChartsOption } from 'echarts';
import ReactECharts from 'echarts-for-react';
import { calculateNiceAxisMax, formatCompactNumber } from '@/lib/utils/metrics';
type TrendChartSeries = {
label: string;
color: string;
@@ -17,17 +19,29 @@ type TrendChartProps = {
labels: string[];
series: TrendChartSeries[];
height?: number;
yAxisValueFormatter?: (value: number) => string;
};
const defaultFormatter = (value: number) => value.toLocaleString('zh-CN');
type TooltipParam = {
axisValueLabel?: string;
color?: string;
seriesName?: string;
value?: number | string | Array<number | string>;
};
export function TrendChart({ labels, series, height = 220 }: TrendChartProps) {
const defaultFormatter = (value: number) => formatCompactNumber(value);
export function TrendChart({
labels,
series,
height = 220,
yAxisValueFormatter,
}: TrendChartProps) {
const option = useMemo<EChartsOption>(() => {
const maxValue =
Math.max(
1,
...series.flatMap((item) => item.values.map((value) => value || 0)),
) * 1.1;
const axisFormatter = yAxisValueFormatter ?? defaultFormatter;
const maxValue = calculateNiceAxisMax(
series.flatMap((item) => item.values),
);
return {
animationDuration: 500,
@@ -47,6 +61,38 @@ export function TrendChart({ labels, series, height = 220 }: TrendChartProps) {
color: '#e2e8f0',
fontSize: 12,
},
formatter: (params: unknown) => {
const items = Array.isArray(params) ? (params as TooltipParam[]) : [];
if (items.length === 0) {
return '';
}
const header = items[0]?.axisValueLabel ?? '';
const rows = items.map((item) => {
const matchedSeries = series.find(
(seriesItem) => seriesItem.label === item.seriesName,
);
const formatter =
matchedSeries?.valueFormatter ??
yAxisValueFormatter ??
defaultFormatter;
const rawValue = Array.isArray(item.value)
? item.value[1]
: item.value;
const numericValue =
typeof rawValue === 'number' ? rawValue : Number(rawValue ?? 0);
return [
'<span style="display:inline-flex;align-items:center;gap:8px;">',
`<span style="display:inline-block;width:8px;height:8px;border-radius:9999px;background:${item.color ?? '#94a3b8'};"></span>`,
`<span>${item.seriesName ?? ''}</span>`,
`<strong style="margin-left:8px;">${formatter(numericValue)}</strong>`,
'</span>',
].join('');
});
return [header, ...rows].join('<br/>');
},
},
legend: {
show: false,
@@ -75,6 +121,7 @@ export function TrendChart({ labels, series, height = 220 }: TrendChartProps) {
splitNumber: 4,
axisLabel: {
color: '#94a3b8',
formatter: (value: number) => axisFormatter(value),
},
splitLine: {
lineStyle: {
@@ -110,7 +157,7 @@ export function TrendChart({ labels, series, height = 220 }: TrendChartProps) {
data: item.values,
})),
};
}, [labels, series]);
}, [labels, series, yAxisValueFormatter]);
if (labels.length === 0 || series.length === 0) {
return (
@@ -20,35 +20,11 @@ import {
getOpenrestyStatusVariant,
} from '@/features/nodes/utils';
import { formatDateTime, formatRelativeTime } from '@/lib/utils/date';
function formatPercent(value?: number | null) {
if (value === undefined || value === null || Number.isNaN(value)) {
return '—';
}
return `${value.toFixed(1)}%`;
}
function formatBytes(value?: number | null) {
if (!value || value <= 0) {
return '—';
}
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let current = value;
let index = 0;
while (current >= 1024 && index < units.length - 1) {
current /= 1024;
index += 1;
}
return `${current.toFixed(current >= 100 || index === 0 ? 0 : 1)} ${units[index]}`;
}
function formatBytesPerSecond(value?: number | null, windowSeconds = 1) {
if (!value || value <= 0 || windowSeconds <= 0) {
return '—';
}
return `${formatBytes(value / windowSeconds)}/s`;
}
import {
formatBytes,
formatBytesPerSecond,
formatPercent,
} from '@/lib/utils/metrics';
function getErrorMessage(error: unknown) {
return error instanceof Error ? error.message : '请求失败,请稍后重试。';
@@ -244,6 +220,7 @@ export function DashboardOverview() {
labels={overview.trends.capacity_24h.map((point) =>
formatTrendHour(point.bucket_started_at),
)}
yAxisValueFormatter={formatPercent}
series={[
{
label: '平均 CPU',
@@ -279,6 +256,7 @@ export function DashboardOverview() {
formatTrendHour(point.bucket_started_at),
)}
height={180}
yAxisValueFormatter={(value) => formatBytesPerSecond(value, 3600)}
series={[
{
label: 'OpenResty 入站',
@@ -306,6 +284,7 @@ export function DashboardOverview() {
formatTrendHour(point.bucket_started_at),
)}
height={180}
yAxisValueFormatter={formatBytes}
series={[
{
label: '磁盘读',
@@ -366,16 +345,14 @@ export function DashboardOverview() {
容量压力节点
</p>
<RankChart
items={buildNodeRankItems(
overview.nodes,
(node) =>
Math.round(
Math.max(
node.cpu_usage_percent,
node.memory_usage_percent,
node.storage_usage_percent,
),
items={buildNodeRankItems(overview.nodes, (node) =>
Math.round(
Math.max(
node.cpu_usage_percent,
node.memory_usage_percent,
node.storage_usage_percent,
),
),
)}
color="#ef4444"
valueFormatter={(value) => `${value}%`}
File diff suppressed because it is too large Load Diff
+83
View File
@@ -0,0 +1,83 @@
const compactNumberFormatter = new Intl.NumberFormat('zh-CN', {
maximumFractionDigits: 1,
});
type FormatBytesOptions = {
emptyText?: string;
zeroText?: string;
};
export function formatCompactNumber(value?: number | null) {
if (value === undefined || value === null || Number.isNaN(value)) {
return '—';
}
return compactNumberFormatter.format(value);
}
export function formatPercent(value?: number | null) {
if (value === undefined || value === null || Number.isNaN(value)) {
return '—';
}
return `${formatCompactNumber(value)}%`;
}
export function formatBytes(
value?: number | null,
options: FormatBytesOptions = {},
) {
const { emptyText = '—', zeroText = '0 B' } = options;
if (value === undefined || value === null || Number.isNaN(value)) {
return emptyText;
}
if (value <= 0) {
return zeroText;
}
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let current = value;
let index = 0;
while (current >= 1024 && index < units.length - 1) {
current /= 1024;
index += 1;
}
const digits = current >= 100 || index === 0 ? 0 : 1;
return `${new Intl.NumberFormat('zh-CN', {
maximumFractionDigits: digits,
minimumFractionDigits: 0,
}).format(current)} ${units[index]}`;
}
export function formatBytesPerSecond(
value?: number | null,
windowSeconds = 1,
options?: FormatBytesOptions,
) {
if (value === undefined || value === null || Number.isNaN(value)) {
return options?.emptyText ?? '—';
}
if (windowSeconds <= 0) {
return options?.emptyText ?? '—';
}
return `${formatBytes(value / windowSeconds, options)}/s`;
}
export function calculateNiceAxisMax(values: number[]) {
const rawMax = Math.max(
0,
...values.map((value) => (Number.isFinite(value) && value > 0 ? value : 0)),
);
if (rawMax <= 0) {
return 1;
}
const paddedMax = rawMax * 1.1;
const magnitude = 10 ** Math.floor(Math.log10(paddedMax));
const normalized = paddedMax / magnitude;
const steps = [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10];
const niceStep = steps.find((step) => normalized <= step) ?? 10;
return niceStep * magnitude;
}
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest';
import {
calculateNiceAxisMax,
formatBytes,
formatBytesPerSecond,
formatPercent,
} from '@/lib/utils/metrics';
describe('metrics utils', () => {
it('formats byte values with readable units', () => {
expect(formatBytes(0)).toBe('0 B');
expect(formatBytes(1536)).toBe('1.5 KB');
expect(formatBytes(183 * 1024 * 1024)).toBe('183 MB');
expect(formatBytes(14.7 * 1024 * 1024)).toBe('14.7 MB');
});
it('formats byte rates with per-second units', () => {
expect(formatBytesPerSecond(0, 3600)).toBe('0 B/s');
expect(formatBytesPerSecond(1630858.9, 3600)).toBe('453 B/s');
expect(formatBytesPerSecond(22620490956.8, 3600)).toBe('6 MB/s');
});
it('formats percent values without long decimals', () => {
expect(formatPercent(58.36809884639982)).toBe('58.4%');
});
it('rounds chart max values to friendly axis steps', () => {
expect(calculateNiceAxisMax([0, 58.36809884639982])).toBe(80);
expect(calculateNiceAxisMax([0, 1630858.9])).toBe(2000000);
expect(calculateNiceAxisMax([0, 22620490956.8])).toBe(25000000000);
});
});