feat(All) 修改结果展示样式,增加测试地区覆盖范围

This commit is contained in:
2025-12-19 15:21:55 +08:00
parent 2f6831336e
commit 1a0815759e
15 changed files with 1336 additions and 368 deletions

View File

@@ -12,11 +12,11 @@ function AppContent() {
const [results, setResults] = useState<Map<string, LatencyResult>>(new Map())
const [testing, setTesting] = useState(false)
const handleTest = useCallback(async (ip: string) => {
const handleTest = useCallback(async (target: string) => {
setTesting(true)
setResults(new Map())
await testAllNodes(ip, (result) => {
await testAllNodes(target, (result) => {
setResults((prev) => new Map(prev).set(result.nodeId, result))
})
@@ -35,7 +35,7 @@ function AppContent() {
<main className="app-main">
<p className="app-description">
Test network latency from global locations to any IP address
Test network latency from global locations to any IP address or domain
</p>
<IpInput onTest={handleTest} testing={testing} />
<LatencyMap results={results} />

View File

@@ -6,10 +6,17 @@ export interface IpInfoResponse {
ip: string
}
export interface LatencyTestResponse {
nodeId: string
latency: number | null
success: boolean
export interface BatchMeasurementResponse {
measurementId: string
}
export interface BatchResultResponse {
status: 'in-progress' | 'finished'
results: Array<{
nodeId: string
latency: number | null
success: boolean
}>
}
export async function fetchUserIp(): Promise<string> {
@@ -19,34 +26,67 @@ export async function fetchUserIp(): Promise<string> {
return data.ip
}
export async function testLatency(
targetIp: string,
nodeId: string
): Promise<LatencyResult> {
const res = await fetch(`${API_BASE}/latency`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetIp, nodeId }),
})
if (!res.ok) {
return { nodeId, latency: null, status: 'failed' }
}
const data: LatencyTestResponse = await res.json()
return {
nodeId: data.nodeId,
latency: data.latency,
status: data.success ? 'success' : 'failed',
}
}
export async function testAllNodes(
targetIp: string,
target: string,
onProgress: (result: LatencyResult) => void
): Promise<void> {
const promises = TEST_NODES.map(async (node) => {
onProgress({ nodeId: node.id, latency: null, status: 'testing' })
const result = await testLatency(targetIp, node.id)
onProgress(result)
for (const node of TEST_NODES) {
onProgress({ nodeId: node.id, latency: null, status: 'pending' })
}
const res = await fetch(`${API_BASE}/latency/batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ target }),
})
await Promise.all(promises)
if (!res.ok) {
for (const node of TEST_NODES) {
onProgress({ nodeId: node.id, latency: null, status: 'failed' })
}
return
}
const { measurementId }: BatchMeasurementResponse = await res.json()
for (const node of TEST_NODES) {
onProgress({ nodeId: node.id, latency: null, status: 'testing' })
}
const startTime = Date.now()
const timeout = 60000
const completedNodes = new Set<string>()
while (Date.now() - startTime < timeout) {
await new Promise(r => setTimeout(r, 800))
const pollRes = await fetch(`${API_BASE}/latency/batch/${measurementId}`)
if (!pollRes.ok) continue
const data: BatchResultResponse = await pollRes.json()
for (const result of data.results) {
if (result.success && !completedNodes.has(result.nodeId)) {
completedNodes.add(result.nodeId)
onProgress({
nodeId: result.nodeId,
latency: result.latency,
status: 'success'
})
}
}
if (data.status === 'finished') {
for (const result of data.results) {
if (!completedNodes.has(result.nodeId)) {
onProgress({
nodeId: result.nodeId,
latency: result.latency,
status: result.success ? 'success' : 'failed'
})
}
}
break
}
}
}

View File

@@ -1,33 +1,42 @@
.ip-input-form {
display: flex;
justify-content: center;
gap: 0;
margin-bottom: 2rem;
flex-wrap: wrap;
position: relative;
max-width: 500px;
margin: 0 auto 3rem;
filter: drop-shadow(var(--shadow-glow));
}
.input-wrapper {
position: relative;
flex: 1;
max-width: 300px;
min-width: 200px;
z-index: 1;
}
.ip-input {
width: 100%;
box-sizing: border-box;
padding: 16px 20px;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 1rem;
padding: 12px 16px;
border-radius: 8px 0 0 8px;
border: 2px solid var(--border-color);
background-color: var(--input-bg);
background: var(--input-bg);
border: 1px solid var(--border-color);
border-right: none;
border-radius: 12px 0 0 12px;
color: var(--text-color);
outline: none;
transition: border-color 0.2s;
transition: all var(--transition-fast);
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
}
.ip-input::placeholder {
color: var(--text-secondary);
opacity: 0.7;
}
.ip-input:focus {
border-color: var(--primary-color);
box-shadow: inset 0 0 20px rgba(56, 189, 248, 0.08);
}
.ip-input-error {
@@ -41,46 +50,86 @@
.error-hint {
position: absolute;
left: 0;
bottom: -20px;
left: 4px;
bottom: -24px;
font-size: 0.75rem;
color: var(--error-color);
font-weight: 500;
}
.test-button {
display: flex;
align-items: center;
gap: 8px;
font-size: 1rem;
padding: 12px 24px;
border-radius: 0 8px 8px 0;
border: 2px solid var(--primary-color);
background-color: var(--primary-color);
color: white;
cursor: pointer;
transition: background-color 0.2s, transform 0.1s;
justify-content: center;
gap: 10px;
padding: 0 32px;
font-weight: 600;
font-size: 0.95rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #fff;
background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
border: 1px solid transparent;
border-radius: 0 12px 12px 0;
cursor: pointer;
transition: all var(--transition-fast);
box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
position: relative;
overflow: hidden;
}
.test-button::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(rgba(255,255,255,0.15), transparent);
opacity: 0;
transition: opacity 0.2s;
}
.test-button:hover:not(:disabled) {
background-color: var(--primary-hover);
border-color: var(--primary-hover);
transform: translateY(-1px);
box-shadow: 0 6px 20px rgba(59, 130, 246, 0.4);
}
.test-button:hover:not(:disabled)::after {
opacity: 1;
}
.test-button:active:not(:disabled) {
transform: scale(0.98);
transform: translateY(1px);
}
.test-button:disabled {
opacity: 0.6;
background: var(--text-secondary);
cursor: not-allowed;
opacity: 0.7;
box-shadow: none;
}
.test-button:disabled::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 50%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
animation: scan 1.5s infinite;
}
@keyframes scan {
100% { left: 200%; }
}
.spinner {
width: 16px;
height: 16px;
border: 2px solid white;
border-top-color: transparent;
width: 18px;
height: 18px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@@ -89,24 +138,22 @@
to { transform: rotate(360deg); }
}
@media (max-width: 480px) {
@media (max-width: 640px) {
.ip-input-form {
flex-direction: column;
align-items: stretch;
gap: 8px;
max-width: 100%;
padding: 0 16px;
}
.input-wrapper {
max-width: none;
}
.ip-input {
border-radius: 8px;
border-radius: 12px 12px 0 0;
border-right: 1px solid var(--border-color);
border-bottom: none;
}
.test-button {
border-radius: 8px;
justify-content: center;
border-radius: 0 0 12px 12px;
padding: 16px;
width: 100%;
}
}

View File

@@ -3,32 +3,39 @@ import { fetchUserIp } from '../api/latency'
import './IpInput.css'
interface IpInputProps {
onTest: (ip: string) => void
onTest: (target: string) => void
testing: boolean
}
const IP_REGEX = /^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/
const DOMAIN_REGEX = /^(?!:\/\/)([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/
function isValidTarget(value: string): boolean {
const trimmed = value.trim().toLowerCase()
return IP_REGEX.test(trimmed) || DOMAIN_REGEX.test(trimmed)
}
export default function IpInput({ onTest, testing }: IpInputProps) {
const [ip, setIp] = useState('')
const [target, setTarget] = useState('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
useEffect(() => {
fetchUserIp()
.then(setIp)
.then(setTarget)
.catch(() => setError('Failed to detect IP'))
.finally(() => setLoading(false))
}, [])
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!IP_REGEX.test(ip)) {
setError('Invalid IP address')
const trimmed = target.trim()
if (!isValidTarget(trimmed)) {
setError('Invalid IP address or domain')
return
}
setError('')
onTest(ip)
onTest(trimmed)
}
return (
@@ -36,18 +43,18 @@ export default function IpInput({ onTest, testing }: IpInputProps) {
<div className="input-wrapper">
<input
type="text"
value={ip}
value={target}
onChange={(e) => {
setIp(e.target.value)
setTarget(e.target.value)
setError('')
}}
placeholder={loading ? 'Detecting IP...' : 'Enter IP address'}
placeholder={loading ? 'Detecting IP...' : 'Enter IP or domain (e.g., 8.8.8.8 or google.com)'}
className={`ip-input ${error ? 'ip-input-error' : ''}`}
disabled={testing || loading}
/>
{error && <span className="error-hint">{error}</span>}
</div>
<button type="submit" className="test-button" disabled={testing || loading || !ip}>
<button type="submit" className="test-button" disabled={testing || loading || !target.trim()}>
{testing ? (
<>
<span className="spinner" />

View File

@@ -1,70 +1,161 @@
.map-container {
position: relative;
width: 100%;
max-width: 900px;
margin: 0 auto 2rem;
border: 1px solid var(--border-color);
border-radius: 12px;
max-width: 1000px;
height: 500px;
margin: 0 auto 3rem;
border-radius: 16px;
overflow: hidden;
background-color: var(--card-bg);
background: #000;
border: 1px solid var(--border-color);
box-shadow: var(--shadow-glow), 0 10px 30px -5px rgba(0, 0, 0, 0.5);
}
.geography {
fill: var(--map-land);
stroke: var(--map-border);
stroke-width: 0.5;
.map-container canvas {
outline: none;
transition: fill 0.2s;
}
.marker-group {
cursor: pointer;
.globe-instructions {
position: absolute;
bottom: 16px;
left: 50%;
transform: translateX(-50%);
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
pointer-events: none;
user-select: none;
background: rgba(0, 0, 0, 0.4);
padding: 6px 14px;
border-radius: 20px;
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
}
.marker-dot {
transition: r 0.3s, fill 0.3s;
.globe-popup {
position: absolute;
top: 20px;
right: 20px;
width: 220px;
background: rgba(15, 23, 42, 0.92);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
padding: 16px;
color: #fff;
animation: slideIn 0.2s ease-out;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5);
z-index: 10;
}
.marker-dot.testing {
animation: pulse 1s ease-in-out infinite;
.popup-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
padding-bottom: 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.marker-label {
font-size: 10px;
.popup-header h3 {
margin: 0;
font-size: 15px;
font-weight: 600;
fill: var(--text-color);
pointer-events: none;
color: #fff;
}
.marker-latency {
.close-btn {
background: none;
border: none;
color: rgba(255, 255, 255, 0.5);
font-size: 20px;
cursor: pointer;
padding: 0;
line-height: 1;
transition: color 0.2s;
}
.close-btn:hover {
color: #fff;
}
.popup-content {
display: flex;
flex-direction: column;
gap: 8px;
}
.popup-row {
display: flex;
justify-content: space-between;
font-size: 13px;
color: rgba(255, 255, 255, 0.7);
}
.popup-row.highlight {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
font-weight: 600;
font-size: 14px;
}
.status-badge {
text-transform: capitalize;
font-size: 11px;
font-weight: 700;
pointer-events: none;
padding: 2px 8px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.1);
}
.marker-inactive {
fill: var(--marker-inactive);
.status-badge.success {
color: #4ade80;
background: rgba(74, 222, 128, 0.15);
}
.pulse-ring {
fill: none;
stroke: var(--primary-color);
stroke-width: 2;
opacity: 0;
animation: pulse-ring 1.5s ease-out infinite;
.status-badge.failed {
color: #f87171;
background: rgba(248, 113, 113, 0.15);
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
.status-badge.testing {
color: #facc15;
background: rgba(250, 204, 21, 0.15);
}
@keyframes pulse-ring {
0% {
r: 8;
opacity: 0.8;
}
100% {
r: 24;
.status-badge.pending {
color: #94a3b8;
background: rgba(148, 163, 184, 0.15);
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (max-width: 768px) {
.map-container {
height: 400px;
}
.globe-popup {
top: 10px;
right: 10px;
width: 180px;
padding: 12px;
}
.popup-header h3 {
font-size: 14px;
}
.popup-row {
font-size: 12px;
}
}

View File

@@ -1,70 +1,143 @@
import { ComposableMap, Geographies, Geography, Marker } from 'react-simple-maps'
import { useMemo, useState, useEffect, useRef } from 'react'
import Globe, { GlobeMethods } from 'react-globe.gl'
import { TEST_NODES, LatencyResult, getLatencyColor } from '@shared/types'
import './LatencyMap.css'
const GEO_URL = 'https://cdn.jsdelivr.net/npm/world-atlas@2/countries-110m.json'
interface LatencyMapProps {
results: Map<string, LatencyResult>
}
export default function LatencyMap({ results }: LatencyMapProps) {
const globeEl = useRef<GlobeMethods | undefined>(undefined)
const [selectedNode, setSelectedNode] = useState<string | null>(null)
const [dimensions, setDimensions] = useState({ width: 0, height: 0 })
const containerRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
setDimensions({
width: entry.contentRect.width,
height: entry.contentRect.height
})
}
})
if (containerRef.current) {
resizeObserver.observe(containerRef.current)
}
return () => resizeObserver.disconnect()
}, [])
useEffect(() => {
if (globeEl.current) {
globeEl.current.controls().autoRotate = true
globeEl.current.controls().autoRotateSpeed = 0.5
}
}, [])
const { pointsData, ringsData } = useMemo(() => {
const points = TEST_NODES.map((node) => {
const result = results.get(node.id)
return {
...node,
lat: node.coords[1],
lng: node.coords[0],
color: getLatencyColor(result?.latency ?? null),
latency: result?.latency ?? null,
status: result?.status ?? 'pending',
size: selectedNode === node.id ? 1.2 : 0.5
}
})
const rings = points.filter(
(p) => p.status === 'testing' || p.status === 'success'
)
return { pointsData: points, ringsData: rings }
}, [results, selectedNode])
const selectedNodeData = selectedNode
? pointsData.find(p => p.id === selectedNode)
: null
return (
<div className="map-container">
<ComposableMap
projectionConfig={{ scale: 140, center: [0, 20] }}
style={{ width: '100%', height: 'auto' }}
>
<Geographies geography={GEO_URL}>
{({ geographies }) =>
geographies.map((geo) => (
<Geography
key={geo.rsmKey}
geography={geo}
className="geography"
/>
))
}
</Geographies>
<div className="map-container" ref={containerRef}>
<Globe
ref={globeEl}
width={dimensions.width}
height={dimensions.height}
globeImageUrl="//unpkg.com/three-globe/example/img/earth-night.jpg"
backgroundImageUrl="//unpkg.com/three-globe/example/img/night-sky.png"
{TEST_NODES.map((node) => {
const result = results.get(node.id)
const isTesting = result?.status === 'testing'
const hasResult = result?.status === 'success' || result?.status === 'failed'
pointsData={pointsData}
pointLat="lat"
pointLng="lng"
pointColor="color"
pointRadius="size"
pointAltitude={0.01}
pointLabel={(d: object) => {
const node = d as typeof pointsData[0]
return `
<div style="color: white; font-family: system-ui; font-size: 12px; padding: 6px 10px; background: rgba(0,0,0,0.85); border-radius: 6px; border: 1px solid rgba(255,255,255,0.1);">
<b>${node.name}</b><br/>
${node.latency ? `${node.latency}ms` : node.status}
</div>
`
}}
onPointClick={(d: object) => {
const node = d as typeof pointsData[0]
setSelectedNode(node.id)
if (globeEl.current) globeEl.current.controls().autoRotate = false
}}
return (
<Marker key={node.id} coordinates={node.coords}>
<g className="marker-group">
{isTesting && (
<circle r={16} className="pulse-ring" />
)}
<circle
r={8}
fill={hasResult ? getLatencyColor(result?.latency ?? null) : 'var(--marker-inactive)'}
className={`marker-dot ${isTesting ? 'testing' : ''}`}
/>
<text
textAnchor="middle"
y={-16}
className="marker-label"
>
{node.name}
</text>
{hasResult && (
<text
textAnchor="middle"
y={24}
className="marker-latency"
fill={getLatencyColor(result?.latency ?? null)}
>
{result?.latency !== null ? `${result.latency}ms` : 'Timeout'}
</text>
)}
</g>
</Marker>
)
})}
</ComposableMap>
ringsData={ringsData}
ringLat="lat"
ringLng="lng"
ringColor="color"
ringMaxRadius={4}
ringPropagationSpeed={2}
ringRepeatPeriod={1200}
atmosphereColor="#3a228a"
atmosphereAltitude={0.15}
/>
{selectedNodeData && (
<div className="globe-popup">
<div className="popup-header">
<h3>{selectedNodeData.name}</h3>
<button className="close-btn" onClick={() => setSelectedNode(null)}>×</button>
</div>
<div className="popup-content">
<div className="popup-row">
<span>Region:</span>
<span>{selectedNodeData.region}</span>
</div>
<div className="popup-row">
<span>Country:</span>
<span>{selectedNodeData.country}</span>
</div>
<div className="popup-row highlight">
<span>Latency:</span>
<span style={{ color: selectedNodeData.color }}>
{selectedNodeData.latency ? `${selectedNodeData.latency}ms` : 'N/A'}
</span>
</div>
<div className="popup-row">
<span>Status:</span>
<span className={`status-badge ${selectedNodeData.status}`}>
{selectedNodeData.status}
</span>
</div>
</div>
</div>
)}
<div className="globe-instructions">
Drag to rotate · Scroll to zoom · Click nodes for details
</div>
</div>
)
}

View File

@@ -1,80 +1,122 @@
.results-panel {
max-width: 900px;
max-width: 1000px;
margin: 0 auto;
animation: fadeIn 0.5s ease-out;
}
.results-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
padding: 0 4px;
align-items: flex-end;
margin-bottom: 1.5rem;
padding: 0 8px;
border-bottom: 1px solid var(--border-color);
padding-bottom: 1rem;
}
.results-header h2 {
margin: 0;
font-size: 1.25rem;
font-size: 1.5rem;
font-weight: 700;
color: var(--text-color);
display: flex;
align-items: center;
gap: 10px;
}
.results-header h2::before {
content: '';
display: block;
width: 4px;
height: 24px;
background: var(--primary-color);
border-radius: 2px;
box-shadow: 0 0 10px var(--primary-color);
}
.avg-latency {
font-size: 1rem;
font-family: 'JetBrains Mono', monospace;
font-size: 0.9rem;
color: var(--text-secondary);
background: var(--card-bg);
padding: 4px 12px;
border-radius: 20px;
border: 1px solid var(--border-color);
}
.results-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 12px;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 16px;
}
.result-card {
background-color: var(--card-bg);
position: relative;
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 12px;
border-radius: 12px;
padding: 16px;
display: flex;
flex-direction: column;
justify-content: space-between;
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
overflow: hidden;
text-align: center;
transition: transform 0.2s, box-shadow 0.2s;
}
.result-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 3px;
background: var(--text-secondary);
opacity: 0.3;
transition: background-color 0.3s, opacity 0.3s, box-shadow 0.3s;
}
.result-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px var(--shadow-color);
transform: translateY(-4px);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
}
.result-card.excellent {
border-color: #22c55e;
}
.result-card.excellent { border-color: rgba(16, 185, 129, 0.3); }
.result-card.excellent::before { background: var(--success-color); opacity: 1; box-shadow: 0 0 10px var(--success-color); }
.result-card.good {
border-color: #eab308;
}
.result-card.good { border-color: rgba(245, 158, 11, 0.3); }
.result-card.good::before { background: var(--warning-color); opacity: 1; box-shadow: 0 0 10px var(--warning-color); }
.result-card.poor {
border-color: #ef4444;
}
.result-card.poor { border-color: rgba(239, 68, 68, 0.3); }
.result-card.poor::before { background: var(--error-color); opacity: 1; box-shadow: 0 0 10px var(--error-color); }
.result-region {
font-size: 0.7rem;
color: var(--text-secondary);
font-size: 0.65rem;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 4px;
letter-spacing: 1px;
color: var(--text-secondary);
margin-bottom: 6px;
opacity: 0.8;
}
.result-name {
font-size: 0.9rem;
font-size: 0.95rem;
font-weight: 600;
color: var(--text-color);
margin-bottom: 8px;
margin-bottom: 12px;
line-height: 1.2;
}
.result-latency {
font-size: 1.1rem;
font-family: 'JetBrains Mono', monospace;
font-size: 1.5rem;
font-weight: 700;
letter-spacing: -1px;
}
.testing-indicator {
font-size: 0.9rem;
color: var(--primary-color);
animation: pulse 1s ease-in-out infinite;
}
@@ -83,6 +125,11 @@
color: var(--text-secondary);
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }

View File

@@ -1,32 +1,57 @@
:root {
/* Core Palette */
--primary-color: #3b82f6;
--primary-hover: #2563eb;
--accent-glow: rgba(59, 130, 246, 0.4);
--success-color: #10b981;
--warning-color: #f59e0b;
--error-color: #ef4444;
/* Text */
--text-color: #1f2937;
--text-secondary: #6b7280;
--background-color: #f9fafb;
--card-bg: #ffffff;
/* Backgrounds */
--background-color: #f3f4f6;
--card-bg: rgba(255, 255, 255, 0.85);
--input-bg: #ffffff;
--border-color: #e5e7eb;
--hover-bg: rgba(0, 0, 0, 0.05);
/* Effects */
--glass-blur: blur(12px);
--shadow-color: rgba(0, 0, 0, 0.1);
--map-land: #e5e7eb;
--map-border: #d1d5db;
--shadow-glow: 0 0 0 transparent;
--transition-fast: 0.2s ease;
--transition-smooth: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
/* Map */
--map-land: #d1d5db;
--map-border: #9ca3af;
--marker-inactive: #9ca3af;
}
[data-theme='dark'] {
--text-color: #f9fafb;
--text-secondary: #9ca3af;
--background-color: #111827;
--card-bg: #1f2937;
--input-bg: #374151;
--border-color: #374151;
--primary-color: #38bdf8;
--primary-hover: #0ea5e9;
--accent-glow: rgba(56, 189, 248, 0.35);
--text-color: #e2e8f0;
--text-secondary: #94a3b8;
--background-color: #0f172a;
--card-bg: rgba(30, 41, 59, 0.75);
--input-bg: rgba(15, 23, 42, 0.9);
--border-color: rgba(148, 163, 184, 0.2);
--hover-bg: rgba(255, 255, 255, 0.1);
--shadow-color: rgba(0, 0, 0, 0.3);
--map-land: #374151;
--map-border: #4b5563;
--marker-inactive: #6b7280;
--shadow-glow: 0 0 20px rgba(56, 189, 248, 0.12);
--map-land: #1e293b;
--map-border: #334155;
--marker-inactive: #475569;
}
* {
@@ -36,11 +61,16 @@
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background-color: var(--background-color);
background-image:
radial-gradient(circle at 50% 0%, rgba(56, 189, 248, 0.08) 0%, transparent 50%),
radial-gradient(circle at 85% 85%, rgba(139, 92, 246, 0.05) 0%, transparent 40%);
background-attachment: fixed;
color: var(--text-color);
line-height: 1.5;
transition: background-color 0.3s, color 0.3s;
line-height: 1.6;
min-height: 100vh;
transition: background-color var(--transition-smooth), color var(--transition-smooth);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@@ -55,26 +85,39 @@ body {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
padding: 1.25rem 2rem;
background: var(--card-bg);
backdrop-filter: var(--glass-blur);
-webkit-backdrop-filter: var(--glass-blur);
border-bottom: 1px solid var(--border-color);
background-color: var(--card-bg);
position: sticky;
top: 0;
z-index: 50;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.07);
}
.app-title {
display: flex;
align-items: center;
gap: 8px;
gap: 12px;
font-size: 1.5rem;
font-weight: 700;
font-weight: 800;
letter-spacing: -0.025em;
background: linear-gradient(135deg, var(--text-color) 0%, var(--primary-color) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.title-icon {
font-size: 1.75rem;
-webkit-text-fill-color: initial;
filter: drop-shadow(0 0 8px var(--accent-glow));
}
.app-main {
flex: 1;
padding: 2rem;
padding: 3rem 2rem;
max-width: 1200px;
margin: 0 auto;
width: 100%;
@@ -83,31 +126,30 @@ body {
.app-description {
text-align: center;
color: var(--text-secondary);
margin-bottom: 1.5rem;
margin-bottom: 2.5rem;
font-size: 1.1rem;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
.app-footer {
text-align: center;
padding: 1rem;
padding: 1.5rem;
border-top: 1px solid var(--border-color);
font-size: 0.85rem;
background: var(--card-bg);
backdrop-filter: var(--glass-blur);
-webkit-backdrop-filter: var(--glass-blur);
font-size: 0.875rem;
color: var(--text-secondary);
}
.app-footer .excellent { color: #22c55e; }
.app-footer .good { color: #eab308; }
.app-footer .poor { color: #ef4444; }
.app-footer .excellent { color: var(--success-color); text-shadow: 0 0 6px var(--success-color); }
.app-footer .good { color: var(--warning-color); text-shadow: 0 0 6px var(--warning-color); }
.app-footer .poor { color: var(--error-color); text-shadow: 0 0 6px var(--error-color); }
@media (max-width: 768px) {
.app-header {
padding: 1rem;
}
.app-title {
font-size: 1.25rem;
}
.app-main {
padding: 1rem;
}
.app-header { padding: 1rem; }
.app-title { font-size: 1.25rem; }
.app-main { padding: 1.5rem 1rem; }
}

View File

@@ -2,6 +2,7 @@ import express, { Request, Response } from 'express'
import cors from 'cors'
import rateLimit from 'express-rate-limit'
import ipaddr from 'ipaddr.js'
import { TEST_NODES } from '../shared/types'
const app = express()
const PORT = process.env.PORT || 3000
@@ -11,25 +12,10 @@ app.use(express.json())
app.use(cors({ origin: 'http://localhost:5173' }))
app.use(rateLimit({
windowMs: 60 * 1000,
limit: 10,
limit: 20,
message: { error: 'Rate limit exceeded' }
}))
interface GlobalPingLocation {
country: string
city?: string
}
const NODE_LOCATIONS: Record<string, GlobalPingLocation> = {
'us-west': { country: 'US', city: 'San Francisco' },
'us-east': { country: 'US', city: 'New York' },
'europe': { country: 'DE', city: 'Frankfurt' },
'asia': { country: 'JP', city: 'Tokyo' },
'south-america': { country: 'BR', city: 'Sao Paulo' },
'africa': { country: 'ZA', city: 'Cape Town' },
'oceania': { country: 'AU', city: 'Sydney' }
}
function extractClientIp(req: Request): string | null {
const forwarded = req.headers['x-forwarded-for']
const raw = typeof forwarded === 'string' ? forwarded.split(',')[0].trim() : req.socket.remoteAddress
@@ -45,38 +31,63 @@ function isPublicIp(ip: string): boolean {
return parsed.range() === 'unicast'
}
const DOMAIN_REGEX = /^(?!:\/\/)([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/
function isValidDomain(domain: string): boolean {
if (domain.length > 253) return false
return DOMAIN_REGEX.test(domain)
}
function isValidTarget(target: string): boolean {
return isPublicIp(target) || isValidDomain(target)
}
interface MeasurementResponse {
id: string
probesCount: number
}
interface ProbeResult {
probe: {
continent: string
country: string
city: string
asn: number
network: string
}
result: {
status: string
rawOutput: string
stats?: {
min: number
max: number
avg: number
total: number
loss: number
}
}
}
interface MeasurementResult {
id: string
type: string
status: 'in-progress' | 'finished'
results?: Array<{
probe: {
continent: string
country: string
city: string
asn: number
network: string
}
result: {
status: string
rawOutput: string
stats?: {
min: number
max: number
avg: number
total: number
loss: number
}
}
}>
results?: ProbeResult[]
}
async function createMeasurement(target: string, location: GlobalPingLocation): Promise<string> {
interface BatchLatencyResult {
nodeId: string
latency: number | null
success: boolean
}
async function createBatchMeasurement(target: string): Promise<string> {
const locations = TEST_NODES.map(node => ({
country: node.country,
city: node.city,
limit: 1
}))
const res = await fetch(`${GLOBALPING_API}/measurements`, {
method: 'POST',
headers: {
@@ -87,7 +98,8 @@ async function createMeasurement(target: string, location: GlobalPingLocation):
body: JSON.stringify({
type: 'ping',
target,
locations: [location],
inProgressUpdates: true,
locations,
measurementOptions: {
packets: 3
}
@@ -103,35 +115,35 @@ async function createMeasurement(target: string, location: GlobalPingLocation):
return data.id
}
async function getMeasurementResult(id: string, timeout = 30000): Promise<{ latency: number | null; success: boolean }> {
const startTime = Date.now()
function normalizeLocationName(value?: string | null): string {
if (!value) return ''
return value
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9]+/g, ' ')
.trim()
.toLowerCase()
}
while (Date.now() - startTime < timeout) {
await new Promise(r => setTimeout(r, 500))
function matchProbeToNode(probe: ProbeResult['probe']): string | null {
const candidates = TEST_NODES.filter(node => node.country === probe.country)
if (candidates.length === 0) return null
const res = await fetch(`${GLOBALPING_API}/measurements/${id}`, {
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'LatencyTest/1.0.0'
const probeCity = normalizeLocationName(probe.city)
if (probeCity) {
for (const node of candidates) {
const nodeCity = normalizeLocationName(node.city)
if (nodeCity && (probeCity.includes(nodeCity) || nodeCity.includes(probeCity))) {
return node.id
}
})
if (!res.ok) {
throw new Error(`Failed to get measurement: ${res.status}`)
}
const data = await res.json() as MeasurementResult
if (data.status !== 'in-progress') {
const result = data.results?.[0]?.result
if (result?.status === 'finished' && result.stats?.avg != null) {
return { latency: Math.round(result.stats.avg), success: true }
}
return { latency: null, success: false }
}
}
return { latency: null, success: false }
if (candidates.length === 1) {
return candidates[0].id
}
return null
}
app.get('/api/ip', (req: Request, res: Response) => {
@@ -142,28 +154,77 @@ app.get('/api/ip', (req: Request, res: Response) => {
res.json({ ip })
})
app.post('/api/latency', async (req: Request, res: Response) => {
const { targetIp, nodeId } = req.body
app.post('/api/latency/batch', async (req: Request, res: Response) => {
const { target } = req.body
if (!targetIp || typeof targetIp !== 'string') {
return res.status(400).json({ error: 'targetIp is required' })
if (!target || typeof target !== 'string') {
return res.status(400).json({ error: 'target is required' })
}
if (!nodeId || !NODE_LOCATIONS[nodeId]) {
return res.status(400).json({ error: `Invalid nodeId. Available: ${Object.keys(NODE_LOCATIONS).join(', ')}` })
}
const trimmedTarget = target.trim().toLowerCase()
if (!isPublicIp(targetIp)) {
return res.status(400).json({ error: 'Invalid or private IP address' })
if (!isValidTarget(trimmedTarget)) {
return res.status(400).json({ error: 'Invalid target. Please enter a valid IP address or domain name.' })
}
try {
const measurementId = await createMeasurement(targetIp, NODE_LOCATIONS[nodeId])
const { latency, success } = await getMeasurementResult(measurementId)
res.json({ nodeId, latency, success })
const measurementId = await createBatchMeasurement(trimmedTarget)
res.json({ measurementId })
} catch (error) {
console.error('Latency test error:', error)
res.status(500).json({ nodeId, latency: null, success: false })
console.error('Batch measurement creation error:', error)
res.status(500).json({ error: 'Failed to create measurement' })
}
})
app.get('/api/latency/batch/:measurementId', async (req: Request, res: Response) => {
const { measurementId } = req.params
try {
const fetchRes = await fetch(`${GLOBALPING_API}/measurements/${measurementId}`, {
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'LatencyTest/1.0.0'
}
})
if (!fetchRes.ok) {
return res.status(fetchRes.status).json({ error: 'Failed to get measurement' })
}
const data = await fetchRes.json() as MeasurementResult
const results: BatchLatencyResult[] = []
const matchedNodes = new Set<string>()
if (data.results) {
for (const probeResult of data.results) {
const result = probeResult.result
const nodeId = matchProbeToNode(probeResult.probe)
if (nodeId && !matchedNodes.has(nodeId)) {
matchedNodes.add(nodeId)
if (result.status === 'finished') {
const latency = result.stats?.avg != null ? Math.round(result.stats.avg) : null
results.push({ nodeId, latency, success: latency !== null })
} else {
results.push({ nodeId, latency: null, success: false })
}
}
}
}
for (const node of TEST_NODES) {
if (!matchedNodes.has(node.id)) {
results.push({ nodeId: node.id, latency: null, success: false })
}
}
res.json({
status: data.status,
results
})
} catch (error) {
console.error('Get measurement error:', error)
res.status(500).json({ error: 'Failed to get measurement' })
}
})

View File

@@ -1,32 +0,0 @@
export const LATENCY_THRESHOLDS = {
excellent: 50,
good: 150,
poor: Infinity,
};
export const TEST_NODES = [
{ id: 'us-west', name: 'US West', region: 'North America', coords: [-122.4194, 37.7749] },
{ id: 'us-east', name: 'US East', region: 'North America', coords: [-74.006, 40.7128] },
{ id: 'europe', name: 'Frankfurt', region: 'Europe', coords: [8.6821, 50.1109] },
{ id: 'asia', name: 'Tokyo', region: 'Asia', coords: [139.6917, 35.6895] },
{ id: 'south-america', name: 'São Paulo', region: 'South America', coords: [-46.6333, -23.5505] },
{ id: 'africa', name: 'Cape Town', region: 'Africa', coords: [18.4241, -33.9249] },
{ id: 'oceania', name: 'Sydney', region: 'Oceania', coords: [151.2093, -33.8688] },
];
export function getLatencyLevel(latency) {
if (latency === null)
return 'poor';
if (latency < LATENCY_THRESHOLDS.excellent)
return 'excellent';
if (latency < LATENCY_THRESHOLDS.good)
return 'good';
return 'poor';
}
export function getLatencyColor(latency) {
const level = getLatencyLevel(latency);
const colors = {
excellent: '#22c55e',
good: '#eab308',
poor: '#ef4444',
};
return colors[level];
}

View File

@@ -3,6 +3,8 @@ export interface TestNode {
name: string
region: string
coords: [number, number] // [longitude, latitude]
country: string
city?: string
}
export interface LatencyResult {
@@ -20,13 +22,27 @@ export const LATENCY_THRESHOLDS = {
} as const
export const TEST_NODES: TestNode[] = [
{ id: 'us-west', name: 'US West', region: 'North America', coords: [-122.4194, 37.7749] },
{ id: 'us-east', name: 'US East', region: 'North America', coords: [-74.006, 40.7128] },
{ id: 'europe', name: 'Frankfurt', region: 'Europe', coords: [8.6821, 50.1109] },
{ id: 'asia', name: 'Tokyo', region: 'Asia', coords: [139.6917, 35.6895] },
{ id: 'south-america', name: 'São Paulo', region: 'South America', coords: [-46.6333, -23.5505] },
{ id: 'africa', name: 'Cape Town', region: 'Africa', coords: [18.4241, -33.9249] },
{ id: 'oceania', name: 'Sydney', region: 'Oceania', coords: [151.2093, -33.8688] },
// North America
{ id: 'us-west', name: 'Los Angeles', region: 'North America', coords: [-118.2437, 34.0522], country: 'US', city: 'Los Angeles' },
{ id: 'us-east', name: 'New York', region: 'North America', coords: [-74.006, 40.7128], country: 'US', city: 'New York' },
{ id: 'us-central', name: 'Dallas', region: 'North America', coords: [-96.797, 32.7767], country: 'US', city: 'Dallas' },
{ id: 'canada', name: 'Toronto', region: 'North America', coords: [-79.3832, 43.6532], country: 'CA', city: 'Toronto' },
// Europe
{ id: 'eu-west', name: 'London', region: 'Europe', coords: [-0.1276, 51.5074], country: 'GB', city: 'London' },
{ id: 'eu-central', name: 'Frankfurt', region: 'Europe', coords: [8.6821, 50.1109], country: 'DE', city: 'Frankfurt' },
{ id: 'eu-north', name: 'Amsterdam', region: 'Europe', coords: [4.9041, 52.3676], country: 'NL', city: 'Amsterdam' },
{ id: 'eu-south', name: 'Paris', region: 'Europe', coords: [2.3522, 48.8566], country: 'FR', city: 'Paris' },
// Asia
{ id: 'asia-east', name: 'Tokyo', region: 'Asia', coords: [139.6917, 35.6895], country: 'JP', city: 'Tokyo' },
{ id: 'asia-se', name: 'Singapore', region: 'Asia', coords: [103.8198, 1.3521], country: 'SG', city: 'Singapore' },
{ id: 'asia-south', name: 'Mumbai', region: 'Asia', coords: [72.8777, 19.076], country: 'IN', city: 'Mumbai' },
{ id: 'asia-hk', name: 'Hong Kong', region: 'Asia', coords: [114.1694, 22.3193], country: 'HK', city: 'Hong Kong' },
// South America
{ id: 'sa-east', name: 'São Paulo', region: 'South America', coords: [-46.6333, -23.5505], country: 'BR', city: 'Sao Paulo' },
// Africa
{ id: 'africa', name: 'Johannesburg', region: 'Africa', coords: [28.0473, -26.2041], country: 'ZA', city: 'Johannesburg' },
// Oceania
{ id: 'oceania', name: 'Sydney', region: 'Oceania', coords: [151.2093, -33.8688], country: 'AU', city: 'Sydney' },
]
export function getLatencyLevel(latency: number | null): LatencyLevel {