| 1 | import React, { useEffect, useState } from "react"; |
| 2 | import { Activity } from "lucide-react"; |
| 3 | import { api } from "./api"; |
| 4 | |
| 5 | export function NetworkLatency({ enabled, revision, selected }) { |
| 6 | const [sample, setSample] = useState(null), |
| 7 | [retry, setRetry] = useState(0); |
| 8 | useEffect(() => { |
| 9 | if (!enabled) return; |
| 10 | let cancelled = false, |
| 11 | timer; |
| 12 | const measure = async () => { |
| 13 | try { |
| 14 | const proxy = await api("/proxy"); |
| 15 | if (cancelled) return; |
| 16 | if (!proxy.active || !proxy.running || !proxy.selected) { |
| 17 | setSample({ label: "延迟 —", detail: "当前代理未连接" }); |
| 18 | } else { |
| 19 | const result = await api("/proxy/delay", { node_id: proxy.selected }); |
| 20 | if (cancelled) return; |
| 21 | const current = await api("/proxy"); |
| 22 | if (cancelled) return; |
| 23 | if ( |
| 24 | !current.active || |
| 25 | !current.running || |
| 26 | current.selected !== proxy.selected || |
| 27 | current.revision !== proxy.revision |
| 28 | ) { |
| 29 | setSample(null); |
| 30 | } else if (Number.isFinite(result.delay) && result.delay > 0) { |
| 31 | setSample({ |
| 32 | label: `${Math.round(result.delay)} ms`, |
| 33 | detail: |
| 34 | "当前节点到 www.gstatic.com 的 HTTP 往返延迟(统一延迟口径),通常不含建连开销,不代表网页首开耗时。每 30 秒更新,点击重新检测;环境联网状态单独检查。", |
| 35 | }); |
| 36 | } else { |
| 37 | setSample({ |
| 38 | label: "延迟不可用", |
| 39 | detail: "当前节点测速未成功,点击重试", |
| 40 | }); |
| 41 | } |
| 42 | } |
| 43 | } catch { |
| 44 | if (!cancelled) |
| 45 | setSample({ |
| 46 | label: "延迟不可用", |
| 47 | detail: "无法测量当前节点延迟,点击重试", |
| 48 | }); |
| 49 | } finally { |
| 50 | if (!cancelled) timer = setTimeout(measure, 30000); |
| 51 | } |
| 52 | }; |
| 53 | measure(); |
| 54 | return () => { |
| 55 | cancelled = true; |
| 56 | clearTimeout(timer); |
| 57 | }; |
| 58 | }, [enabled, revision, selected, retry]); |
| 59 | return ( |
| 60 | <button |
| 61 | className="status-latency" |
| 62 | aria-label={`网络延迟:${enabled ? sample?.label || "检测中" : "未连接"}`} |
| 63 | title={ |
| 64 | enabled |
| 65 | ? sample?.detail || "正在检测当前节点的网络延迟" |
| 66 | : "环境启动并连接代理后检测网络延迟" |
| 67 | } |
| 68 | disabled={!enabled} |
| 69 | onClick={() => { |
| 70 | setSample(null); |
| 71 | setRetry((value) => value + 1); |
| 72 | }} |
| 73 | > |
| 74 | <Activity size={12} /> |
| 75 | <span>{enabled ? sample?.label || "测延迟…" : "延迟 —"}</span> |
| 76 | </button> |
| 77 | ); |
| 78 | } |