A modern and elegant dashboard for network traffic visualization and analysis.
feat(web): live upload/download speed and a speed view for the trend chart (#93)
luoleia8b39fe09a2c
diff --git a/apps/web/app/[locale]/dashboard/components/content/index.tsx b/apps/web/app/[locale]/dashboard/components/content/index.tsxindex d70fbce..2ed2ff8 100644--- a/apps/web/app/[locale]/dashboard/components/content/index.tsx+++ b/apps/web/app/[locale]/dashboard/components/content/index.tsx@@ -22,6 +22,7 @@ import { InsightThreePanelSkeleton } from "@/components/ui/insight-skeleton";import { api, type TimeRange } from "@/lib/api";import { getDevicesQueryKey } from "@/lib/stats-query-keys";import { useStableTimeRange } from "@/lib/hooks/use-stable-time-range";+import { useTransferRate } from "@/lib/transfer-rate";import { cn } from "@/lib/utils";import type { BackendStatus, TabId, TimePreset } from "@/lib/types/dashboard";import type {@@ -71,6 +72,16 @@ const OverviewContent = memo(function OverviewContent({backendStatus: BackendStatus;isLoading?: boolean;}) {+ // Live rate only makes sense while the window ends at "now" (issue #93);+ // every preset except "custom" does.+ const stableRange = useStableTimeRange(timeRange, { roundToMinute: true });+ const isLiveWindow = autoRefresh && timePreset !== "custom";+ const rate = useTransferRate(data?.totalDownload, data?.totalUpload, {+ windowKey: `${stableRange?.start ?? ""}|${stableRange?.end ?? ""}`,+ sourceKey: String(activeBackendId ?? ""),+ enabled: isLiveWindow && !!activeBackendId,+ });+return (<div className="space-y-6"><StatsCards@@ -78,6 +89,7 @@ const OverviewContent = memo(function OverviewContent({error={error}backendStatus={backendStatus}isLoading={isLoading}+ rate={isLiveWindow ? rate : undefined}/><OverviewTabdomains={data?.topDomains || []}diff --git a/apps/web/components/features/stats/charts/trend-chart.tsx b/apps/web/components/features/stats/charts/trend-chart.tsxindex fed1e43..1d6649e 100644--- a/apps/web/components/features/stats/charts/trend-chart.tsx+++ b/apps/web/components/features/stats/charts/trend-chart.tsx@@ -1,6 +1,6 @@"use client";-import React, { useMemo, useRef } from "react";+import React, { useMemo, useRef, useState } from "react";import {AreaChart,Area,@@ -14,15 +14,18 @@ import { Activity, Clock, BarChart3, Loader2 } from "lucide-react";import { useTranslations } from "next-intl";import { Button } from "@/components/ui/button";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";-import { cn, formatBytes } from "@/lib/utils";+import { cn, formatBytes, formatBytesPerSecond } from "@/lib/utils";import type { TrafficTrendPoint } from "@neko-master/shared";type TimeRange = "30m" | "1h" | "24h" | "today";type TrendGranularity = "minute" | "day";+type TrendMode = "traffic" | "speed";interface TrafficTrendChartProps {data: TrafficTrendPoint[];granularity: TrendGranularity;+ /** Bucket size of `data`, used to turn bytes per bucket into bytes/s. */+ bucketMinutes?: number;timeRange?: TimeRange;timeRangeOptions?: TimeRange[];onTimeRangeChange?: (range: TimeRange) => void;@@ -34,6 +37,7 @@ export const TrafficTrendChart = React.memo(function TrafficTrendChart({data,granularity,+ bucketMinutes = 1,timeRange,timeRangeOptions = [],onTimeRangeChange,@@ -42,6 +46,9 @@ export const TrafficTrendChart = React.memo(}: TrafficTrendChartProps) {const t = useTranslations("trend");const chartT = useTranslations("chart");+ const [mode, setMode] = useState<TrendMode>("traffic");+ const bucketSeconds = Math.max(60, Math.round(bucketMinutes * 60));+ const formatValue = mode === "speed" ? formatBytesPerSecond : formatBytes;// Track if we've ever received data to avoid showing empty state on initial loadconst hasEverReceivedData = useRef(false);@@ -101,15 +108,16 @@ export const TrafficTrendChart = React.memo(minute: "2-digit",hour12: false,});+ const scale = mode === "speed" ? bucketSeconds : 1;return {time: point.time,- download: point.download,- upload: point.upload,+ download: point.download / scale,+ upload: point.upload / scale,timeLabel,timestamp: date.getTime(), // for sorting/debugging};});- }, [data, granularity]);+ }, [data, granularity, mode, bucketSeconds]);// Custom tooltip - show local timeconst CustomTooltip = React.useCallback(@@ -144,7 +152,7 @@ export const TrafficTrendChart = React.memo({chartT("download")}:</span><span className="font-medium tabular-nums">- {formatBytes(dataPoint.download)}+ {formatValue(dataPoint.download)}</span></p><p className="text-sm flex items-center gap-2">@@ -153,14 +161,14 @@ export const TrafficTrendChart = React.memo({chartT("upload")}:</span><span className="font-medium tabular-nums">- {formatBytes(dataPoint.upload)}+ {formatValue(dataPoint.upload)}</span></p><p className="text-sm flex items-center gap-2 pt-1 border-t border-border/50 mt-1"><span className="w-2 h-2 rounded-full bg-transparent" /><span className="text-muted-foreground">{t("total")}:</span><span className="font-semibold tabular-nums">- {formatBytes(dataPoint.download + dataPoint.upload)}+ {formatValue(dataPoint.download + dataPoint.upload)}</span></p></div>@@ -169,7 +177,7 @@ export const TrafficTrendChart = React.memo(}return null;},- [chartT, t, granularity],+ [chartT, t, granularity, formatValue],);// Loading skeleton - show when loading or on initial load with no data yet@@ -256,6 +264,28 @@ export const TrafficTrendChart = React.memo(</CardTitle><div className="flex items-center gap-2">+ <div+ role="radiogroup"+ aria-label={t("modeLabel")}+ className="flex items-center gap-0.5 bg-muted/50 rounded-lg p-0.5">+ {(["traffic", "speed"] as const).map((option) => (+ <Button+ key={option}+ variant="ghost"+ size="sm"+ role="radio"+ aria-checked={mode === option}+ className={cn(+ "h-7 px-3 text-xs rounded-md transition-all",+ mode === option+ ? "bg-background shadow-sm text-primary font-medium"+ : "text-muted-foreground hover:text-foreground",+ )}+ onClick={() => setMode(option)}>+ {option === "traffic" ? t("modeTraffic") : t("modeSpeed")}+ </Button>+ ))}+ </div><div className={selectorSlotClassName}>{showTimeRangeSelector ? (<div className="flex items-center gap-0.5 bg-muted/50 rounded-lg p-0.5">@@ -393,9 +423,9 @@ export const TrafficTrendChart = React.memo(tickLine={false}tick={{ fontSize: 10, fill: "#888888" }}tickFormatter={(value) =>- formatBytes(value).replace(" ", "")+ formatValue(value).replace(" ", "")}- width={50}+ width={mode === "speed" ? 62 : 50}/><Tooltip content={<CustomTooltip />} /><Area@@ -439,6 +469,7 @@ export const TrafficTrendChart = React.memo(return (JSON.stringify(prev.data) === JSON.stringify(next.data) &&prev.granularity === next.granularity &&+ prev.bucketMinutes === next.bucketMinutes &&prev.timeRange === next.timeRange &&JSON.stringify(prev.timeRangeOptions) ===JSON.stringify(next.timeRangeOptions) &&diff --git a/apps/web/components/features/stats/stats-cards.tsx b/apps/web/components/features/stats/stats-cards.tsxindex 0311627..dbc5f69 100644--- a/apps/web/components/features/stats/stats-cards.tsx+++ b/apps/web/components/features/stats/stats-cards.tsx@@ -4,7 +4,8 @@ import { useRef, useEffect } from "react";import { Download, Upload, Globe, Activity, Server, Route, AlertTriangle } from "lucide-react";import { useTranslations, useLocale } from "next-intl";import { animate, motion, useTransform, useMotionValue } from "framer-motion";-import { formatBytes, cn } from "@/lib/utils";+import { formatBytes, formatBytesPerSecond, cn } from "@/lib/utils";+import type { TransferRate } from "@/lib/transfer-rate";import type { StatsSummary } from "@neko-master/shared";interface StatsCardsProps {@@ -12,6 +13,8 @@ interface StatsCardsProps {error?: string | null;backendStatus?: "healthy" | "unhealthy" | "unknown";isLoading?: boolean;+ /** Live rate for the latest window; undefined hides the rate line. */+ rate?: TransferRate | null;}// ---------- Animated number display ----------@@ -76,7 +79,7 @@ function AnimatedStatCard({value: number;formatter: (n: number) => string;label: string;- subvalue?: string;+ subvalue?: React.ReactNode;icon: React.ElementType;color: string;}) {@@ -98,7 +101,7 @@ function AnimatedStatCard({title={formatter(value)}/>{subvalue && (- <p className="text-base text-muted-foreground mt-1.5 truncate">+ <p className="text-[11px] text-muted-foreground mt-1.5 truncate tabular-nums">{subvalue}</p>)}@@ -109,7 +112,23 @@ function AnimatedStatCard({// ---------- Main -----------export function StatsCards({ data, backendStatus, isLoading, error }: StatsCardsProps) {+function RateLine({ value, label }: { value: number | null; label: string }) {+ return (+ <span className="inline-flex items-center gap-1.5" title={label}>+ <span+ aria-hidden+ className={cn(+ "w-1.5 h-1.5 rounded-full",+ value === null ? "bg-muted-foreground/40" : "bg-emerald-500 dark:bg-emerald-400",+ )}+ />+ <span className="sr-only">{label}: </span>+ {value === null ? "—" : formatBytesPerSecond(value)}+ </span>+ );+}++export function StatsCards({ data, backendStatus, isLoading, error, rate }: StatsCardsProps) {const t = useTranslations("stats");const locale = useLocale();const formatCount = (n: number) => n.toLocaleString(locale);@@ -207,6 +226,11 @@ export function StatsCards({ data, backendStatus, isLoading, error }: StatsCardsformatter={formatBytes}icon={Download}label={t("totalDownload")}+ subvalue={+ rate !== undefined ? (+ <RateLine value={rate?.download ?? null} label={t("currentDownload")} />+ ) : undefined+ }color="#3B82F6"/><AnimatedStatCard@@ -214,6 +238,11 @@ export function StatsCards({ data, backendStatus, isLoading, error }: StatsCardsformatter={formatBytes}icon={Upload}label={t("totalUpload")}+ subvalue={+ rate !== undefined ? (+ <RateLine value={rate?.upload ?? null} label={t("currentUpload")} />+ ) : undefined+ }color="#8B5CF6"/><AnimatedStatCarddiff --git a/apps/web/components/overview/index.tsx b/apps/web/components/overview/index.tsxindex b9a79f6..8f25932 100644--- a/apps/web/components/overview/index.tsx+++ b/apps/web/components/overview/index.tsx@@ -296,6 +296,7 @@ export function OverviewTab({<TrafficTrendChartdata={trendData || []}granularity={trendGranularity}+ bucketMinutes={trendQuery.bucketMinutes}timeRange={canUseTrendSelector ? trendTimeRange : undefined}timeRangeOptions={trendTimeOptions}onTimeRangeChange={canUseTrendSelector ? handleTimeRangeChange : undefined}diff --git a/apps/web/lib/transfer-rate.ts b/apps/web/lib/transfer-rate.tsnew file mode 100644index 0000000..6103c73--- /dev/null+++ b/apps/web/lib/transfer-rate.ts@@ -0,0 +1,111 @@+"use client";++import { useEffect, useRef, useState } from "react";++// Live transfer rate derived from successive cumulative totals (issue #93).+// Summary pushes arrive every few seconds, so the rate is averaged over a+// short sliding window instead of a single noisy delta.++export interface TotalsSample {+ at: number;+ download: number;+ upload: number;+}++export interface TransferRate {+ download: number;+ upload: number;+}++export const RATE_WINDOW_MS = 15_000;+const MIN_SPAN_MS = 2_000;+const MAX_SAMPLE_AGE_MS = 30_000;++/**+ * Append a sample and drop the window when totals go backwards (range or+ * backend switched underneath us) or when the previous sample is stale.+ */+export function pushSample(samples: TotalsSample[], next: TotalsSample): TotalsSample[] {+ const last = samples[samples.length - 1];+ if (+ last &&+ (next.download < last.download ||+ next.upload < last.upload ||+ next.at - last.at > MAX_SAMPLE_AGE_MS ||+ next.at < last.at)+ ) {+ return [next];+ }+ if (last && next.download === last.download && next.upload === last.upload && next.at === last.at) {+ return samples;+ }+ const kept = samples.filter((sample) => next.at - sample.at <= RATE_WINDOW_MS);+ return [...kept, next];+}++/** Bytes per second over the window, or null when there is not enough data. */+export function computeRate(samples: TotalsSample[], now: number): TransferRate | null {+ if (samples.length < 2) return null;+ const first = samples[0];+ const last = samples[samples.length - 1];+ if (now - last.at > MAX_SAMPLE_AGE_MS) return null;+ const spanMs = last.at - first.at;+ if (spanMs < MIN_SPAN_MS) return null;+ return {+ download: Math.max(0, ((last.download - first.download) * 1000) / spanMs),+ upload: Math.max(0, ((last.upload - first.upload) * 1000) / spanMs),+ };+}++/**+ * Track the live rate of cumulative totals.+ * - `windowKey` changes when the queried window moves (rolling presets shift+ * every minute): samples restart, but the last reading stays on screen+ * until a new one is available or it goes stale.+ * - `sourceKey` changes when the totals belong to something else (backend+ * switched): samples and the displayed reading are both cleared.+ */+export function useTransferRate(+ download: number | undefined,+ upload: number | undefined,+ { windowKey, sourceKey, enabled }: { windowKey: string; sourceKey: string; enabled: boolean },+): TransferRate | null {+ const samplesRef = useRef<TotalsSample[]>([]);+ const windowKeyRef = useRef(windowKey);+ const sourceKeyRef = useRef(sourceKey);+ const lastReadingAtRef = useRef(0);+ const [rate, setRate] = useState<TransferRate | null>(null);++ useEffect(() => {+ if (sourceKeyRef.current !== sourceKey || !enabled) {+ sourceKeyRef.current = sourceKey;+ windowKeyRef.current = windowKey;+ samplesRef.current = [];+ setRate(null);+ } else if (windowKeyRef.current !== windowKey) {+ windowKeyRef.current = windowKey;+ samplesRef.current = [];+ }+ if (!enabled || download === undefined || upload === undefined) return;+ const now = Date.now();+ samplesRef.current = pushSample(samplesRef.current, { at: now, download, upload });+ const next = computeRate(samplesRef.current, now);+ if (next) {+ lastReadingAtRef.current = now;+ setRate(next);+ }+ }, [download, upload, windowKey, sourceKey, enabled]);++ // Expire the reading when pushes stop arriving.+ useEffect(() => {+ if (!enabled) return;+ const timer = setInterval(() => {+ if (Date.now() - lastReadingAtRef.current > MAX_SAMPLE_AGE_MS) {+ setRate((current) => (current ? null : current));+ }+ }, 5_000);+ return () => clearInterval(timer);+ }, [enabled]);++ return rate;+}diff --git a/apps/web/lib/utils.ts b/apps/web/lib/utils.tsindex 82689a1..7415012 100644--- a/apps/web/lib/utils.ts+++ b/apps/web/lib/utils.ts@@ -72,3 +72,7 @@ export function formatDuration(dateString: string): string {if (minutes > 0) return `${minutes}m ago`;return `${seconds}s ago`;}++export function formatBytesPerSecond(bytesPerSecond: number): string {+ return `${formatBytes(bytesPerSecond)}/s`;+}diff --git a/apps/web/messages/en.json b/apps/web/messages/en.jsonindex 9ab567d..c80ef9f 100644--- a/apps/web/messages/en.json+++ b/apps/web/messages/en.json@@ -100,7 +100,9 @@"upload": "Upload","tracked": "tracked","unavailable": "Waiting for backend",- "loadErrorTitle": "Failed to load statistics"+ "loadErrorTitle": "Failed to load statistics",+ "currentDownload": "Current download speed",+ "currentUpload": "Current upload speed"},"chart": {"trafficHistory": "Traffic History (24h)",@@ -118,7 +120,10 @@"total": "Total","noData": "No data","noDataHint": "Try switching to a shorter range or wait for new traffic.",- "loading": "Loading..."+ "loading": "Loading...",+ "modeLabel": "Chart mode",+ "modeTraffic": "Traffic",+ "modeSpeed": "Speed"},"topDomains": {"title": "Top Domains",@@ -170,7 +175,6 @@"ipCount": "IPs","proxy": "Proxy","proxyTraffic": "Proxy Traffic Breakdown",-"domainsCount": "domains","showing": "Showing","of": "of",diff --git a/apps/web/messages/zh.json b/apps/web/messages/zh.jsonindex 10b7689..4a63225 100644--- a/apps/web/messages/zh.json+++ b/apps/web/messages/zh.json@@ -100,7 +100,9 @@"upload": "上传","tracked": "已追踪","unavailable": "等待后端恢复",- "loadErrorTitle": "统计数据加载失败"+ "loadErrorTitle": "统计数据加载失败",+ "currentDownload": "当前下载速度",+ "currentUpload": "当前上传速度"},"chart": {"trafficHistory": "流量趋势 (24小时)",@@ -118,7 +120,10 @@"total": "总计","noData": "暂无数据","noDataHint": "可尝试切换更短时间范围,或等待新流量数据。",- "loading": "加载中..."+ "loading": "加载中...",+ "modeLabel": "图表模式",+ "modeTraffic": "流量",+ "modeSpeed": "网速"},"topDomains": {"title": "热门域名",@@ -169,7 +174,6 @@"ipCount": "IP数","proxy": "代理节点","proxyTraffic": "代理节点流量明细",-"domainsCount": "个域名","showing": "显示","of": "共",