feat(All): 第一版项目

This commit is contained in:
2025-12-19 09:33:04 +08:00
parent 154132f17e
commit 2f6831336e
35 changed files with 5120 additions and 0 deletions

58
src/client/App.tsx Normal file
View File

@@ -0,0 +1,58 @@
import { useState, useCallback } from 'react'
import { ThemeProvider } from './contexts/ThemeContext'
import ThemeSwitcher from './components/ThemeSwitcher'
import IpInput from './components/IpInput'
import LatencyMap from './components/LatencyMap'
import ResultsPanel from './components/ResultsPanel'
import { testAllNodes } from './api/latency'
import { LatencyResult } from '@shared/types'
import './styles/index.css'
function AppContent() {
const [results, setResults] = useState<Map<string, LatencyResult>>(new Map())
const [testing, setTesting] = useState(false)
const handleTest = useCallback(async (ip: string) => {
setTesting(true)
setResults(new Map())
await testAllNodes(ip, (result) => {
setResults((prev) => new Map(prev).set(result.nodeId, result))
})
setTesting(false)
}, [])
return (
<div className="app">
<header className="app-header">
<h1 className="app-title">
<span className="title-icon">🌐</span>
Latency Test
</h1>
<ThemeSwitcher />
</header>
<main className="app-main">
<p className="app-description">
Test network latency from global locations to any IP address
</p>
<IpInput onTest={handleTest} testing={testing} />
<LatencyMap results={results} />
<ResultsPanel results={results} />
</main>
<footer className="app-footer">
<p>Latency thresholds: <span className="excellent"></span> &lt;50ms <span className="good"></span> 50-150ms <span className="poor"></span> &gt;150ms</p>
</footer>
</div>
)
}
export default function App() {
return (
<ThemeProvider>
<AppContent />
</ThemeProvider>
)
}

52
src/client/api/latency.ts Normal file
View File

@@ -0,0 +1,52 @@
import { LatencyResult, TEST_NODES } from '@shared/types'
const API_BASE = '/api'
export interface IpInfoResponse {
ip: string
}
export interface LatencyTestResponse {
nodeId: string
latency: number | null
success: boolean
}
export async function fetchUserIp(): Promise<string> {
const res = await fetch(`${API_BASE}/ip`)
if (!res.ok) throw new Error('Failed to fetch IP')
const data: IpInfoResponse = await res.json()
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,
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)
})
await Promise.all(promises)
}

View File

@@ -0,0 +1,112 @@
.ip-input-form {
display: flex;
justify-content: center;
gap: 0;
margin-bottom: 2rem;
flex-wrap: wrap;
}
.input-wrapper {
position: relative;
flex: 1;
max-width: 300px;
min-width: 200px;
}
.ip-input {
width: 100%;
box-sizing: border-box;
font-size: 1rem;
padding: 12px 16px;
border-radius: 8px 0 0 8px;
border: 2px solid var(--border-color);
background-color: var(--input-bg);
color: var(--text-color);
outline: none;
transition: border-color 0.2s;
}
.ip-input:focus {
border-color: var(--primary-color);
}
.ip-input-error {
border-color: var(--error-color);
}
.ip-input:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.error-hint {
position: absolute;
left: 0;
bottom: -20px;
font-size: 0.75rem;
color: var(--error-color);
}
.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;
font-weight: 600;
}
.test-button:hover:not(:disabled) {
background-color: var(--primary-hover);
border-color: var(--primary-hover);
}
.test-button:active:not(:disabled) {
transform: scale(0.98);
}
.test-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.spinner {
width: 16px;
height: 16px;
border: 2px solid white;
border-top-color: transparent;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@media (max-width: 480px) {
.ip-input-form {
flex-direction: column;
align-items: stretch;
gap: 8px;
padding: 0 16px;
}
.input-wrapper {
max-width: none;
}
.ip-input {
border-radius: 8px;
}
.test-button {
border-radius: 8px;
justify-content: center;
}
}

View File

@@ -0,0 +1,62 @@
import { useState, useEffect } from 'react'
import { fetchUserIp } from '../api/latency'
import './IpInput.css'
interface IpInputProps {
onTest: (ip: 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)$/
export default function IpInput({ onTest, testing }: IpInputProps) {
const [ip, setIp] = useState('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
useEffect(() => {
fetchUserIp()
.then(setIp)
.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')
return
}
setError('')
onTest(ip)
}
return (
<form onSubmit={handleSubmit} className="ip-input-form">
<div className="input-wrapper">
<input
type="text"
value={ip}
onChange={(e) => {
setIp(e.target.value)
setError('')
}}
placeholder={loading ? 'Detecting IP...' : 'Enter IP address'}
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}>
{testing ? (
<>
<span className="spinner" />
Testing...
</>
) : (
'Test Latency'
)}
</button>
</form>
)
}

View File

@@ -0,0 +1,70 @@
.map-container {
width: 100%;
max-width: 900px;
margin: 0 auto 2rem;
border: 1px solid var(--border-color);
border-radius: 12px;
overflow: hidden;
background-color: var(--card-bg);
}
.geography {
fill: var(--map-land);
stroke: var(--map-border);
stroke-width: 0.5;
outline: none;
transition: fill 0.2s;
}
.marker-group {
cursor: pointer;
}
.marker-dot {
transition: r 0.3s, fill 0.3s;
}
.marker-dot.testing {
animation: pulse 1s ease-in-out infinite;
}
.marker-label {
font-size: 10px;
font-weight: 600;
fill: var(--text-color);
pointer-events: none;
}
.marker-latency {
font-size: 11px;
font-weight: 700;
pointer-events: none;
}
.marker-inactive {
fill: var(--marker-inactive);
}
.pulse-ring {
fill: none;
stroke: var(--primary-color);
stroke-width: 2;
opacity: 0;
animation: pulse-ring 1.5s ease-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
@keyframes pulse-ring {
0% {
r: 8;
opacity: 0.8;
}
100% {
r: 24;
opacity: 0;
}
}

View File

@@ -0,0 +1,70 @@
import { ComposableMap, Geographies, Geography, Marker } from 'react-simple-maps'
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) {
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>
{TEST_NODES.map((node) => {
const result = results.get(node.id)
const isTesting = result?.status === 'testing'
const hasResult = result?.status === 'success' || result?.status === 'failed'
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>
</div>
)
}

View File

@@ -0,0 +1,89 @@
.results-panel {
max-width: 900px;
margin: 0 auto;
}
.results-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
padding: 0 4px;
}
.results-header h2 {
margin: 0;
font-size: 1.25rem;
color: var(--text-color);
}
.avg-latency {
font-size: 1rem;
color: var(--text-secondary);
}
.results-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 12px;
}
.result-card {
background-color: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 12px;
text-align: center;
transition: transform 0.2s, box-shadow 0.2s;
}
.result-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px var(--shadow-color);
}
.result-card.excellent {
border-color: #22c55e;
}
.result-card.good {
border-color: #eab308;
}
.result-card.poor {
border-color: #ef4444;
}
.result-region {
font-size: 0.7rem;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 4px;
}
.result-name {
font-size: 0.9rem;
font-weight: 600;
color: var(--text-color);
margin-bottom: 8px;
}
.result-latency {
font-size: 1.1rem;
font-weight: 700;
}
.testing-indicator {
color: var(--primary-color);
animation: pulse 1s ease-in-out infinite;
}
.pending {
color: var(--text-secondary);
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}

View File

@@ -0,0 +1,71 @@
import { TEST_NODES, LatencyResult, getLatencyColor, getLatencyLevel } from '@shared/types'
import './ResultsPanel.css'
interface ResultsPanelProps {
results: Map<string, LatencyResult>
}
export default function ResultsPanel({ results }: ResultsPanelProps) {
if (results.size === 0) return null
const sortedNodes = [...TEST_NODES].sort((a, b) => {
const aResult = results.get(a.id)
const bResult = results.get(b.id)
const aLatency = aResult?.latency ?? Infinity
const bLatency = bResult?.latency ?? Infinity
return aLatency - bLatency
})
const completedResults = sortedNodes
.map((node) => ({ node, result: results.get(node.id) }))
.filter(({ result }) => result?.status === 'success' || result?.status === 'failed')
const avgLatency =
completedResults.length > 0
? Math.round(
completedResults
.filter(({ result }) => result?.latency !== null)
.reduce((sum, { result }) => sum + (result?.latency ?? 0), 0) /
completedResults.filter(({ result }) => result?.latency !== null).length
)
: null
return (
<div className="results-panel">
<div className="results-header">
<h2>Test Results</h2>
{avgLatency !== null && (
<div className="avg-latency">
Avg: <span style={{ color: getLatencyColor(avgLatency) }}>{avgLatency}ms</span>
</div>
)}
</div>
<div className="results-grid">
{sortedNodes.map((node) => {
const result = results.get(node.id)
const isTesting = result?.status === 'testing'
const hasResult = result?.status === 'success' || result?.status === 'failed'
return (
<div key={node.id} className={`result-card ${hasResult ? getLatencyLevel(result?.latency ?? null) : ''}`}>
<div className="result-region">{node.region}</div>
<div className="result-name">{node.name}</div>
<div className="result-latency">
{isTesting ? (
<span className="testing-indicator">Testing...</span>
) : hasResult ? (
<span style={{ color: getLatencyColor(result?.latency ?? null) }}>
{result?.latency !== null ? `${result.latency}ms` : 'Timeout'}
</span>
) : (
<span className="pending"></span>
)}
</div>
</div>
)
})}
</div>
</div>
)
}

View File

@@ -0,0 +1,17 @@
.theme-switcher {
background: transparent;
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 8px 12px;
font-size: 1.25rem;
cursor: pointer;
transition: background-color 0.2s, transform 0.1s;
}
.theme-switcher:hover {
background-color: var(--hover-bg);
}
.theme-switcher:active {
transform: scale(0.95);
}

View File

@@ -0,0 +1,16 @@
import { useTheme } from '../contexts/ThemeContext'
import './ThemeSwitcher.css'
export default function ThemeSwitcher() {
const { theme, toggleTheme } = useTheme()
return (
<button
onClick={toggleTheme}
className="theme-switcher"
aria-label={`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}
>
{theme === 'light' ? '🌙' : '☀️'}
</button>
)
}

View File

@@ -0,0 +1,37 @@
import { createContext, useContext, useEffect, useState, ReactNode } from 'react'
type Theme = 'light' | 'dark'
interface ThemeContextValue {
theme: Theme
toggleTheme: () => void
}
const ThemeContext = createContext<ThemeContextValue | null>(null)
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>(() => {
const saved = localStorage.getItem('theme') as Theme
if (saved) return saved
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
})
useEffect(() => {
document.documentElement.setAttribute('data-theme', theme)
localStorage.setItem('theme', theme)
}, [theme])
const toggleTheme = () => setTheme(t => (t === 'light' ? 'dark' : 'light'))
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
)
}
export function useTheme() {
const ctx = useContext(ThemeContext)
if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
return ctx
}

9
src/client/main.tsx Normal file
View File

@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)

59
src/client/react-simple-maps.d.ts vendored Normal file
View File

@@ -0,0 +1,59 @@
declare module 'react-simple-maps' {
import { ComponentType, ReactNode } from 'react'
interface ComposableMapProps {
projection?: string
projectionConfig?: {
scale?: number
center?: [number, number]
rotate?: [number, number, number]
}
width?: number
height?: number
style?: React.CSSProperties
children?: ReactNode
}
interface GeographiesProps {
geography: string | object
children: (data: { geographies: Geography[] }) => ReactNode
}
interface Geography {
rsmKey: string
properties: Record<string, unknown>
}
interface GeographyProps {
geography: Geography
style?: {
default?: React.CSSProperties
hover?: React.CSSProperties
pressed?: React.CSSProperties
}
className?: string
onClick?: (event: React.MouseEvent) => void
onMouseEnter?: (event: React.MouseEvent) => void
onMouseLeave?: (event: React.MouseEvent) => void
}
interface MarkerProps {
coordinates: [number, number]
children?: ReactNode
}
interface LineProps {
from: [number, number]
to: [number, number]
stroke?: string
strokeWidth?: number
strokeLinecap?: string
strokeDasharray?: string
}
export const ComposableMap: ComponentType<ComposableMapProps>
export const Geographies: ComponentType<GeographiesProps>
export const Geography: ComponentType<GeographyProps>
export const Marker: ComponentType<MarkerProps>
export const Line: ComponentType<LineProps>
}

113
src/client/styles/index.css Normal file
View File

@@ -0,0 +1,113 @@
:root {
--primary-color: #3b82f6;
--primary-hover: #2563eb;
--error-color: #ef4444;
--text-color: #1f2937;
--text-secondary: #6b7280;
--background-color: #f9fafb;
--card-bg: #ffffff;
--input-bg: #ffffff;
--border-color: #e5e7eb;
--hover-bg: rgba(0, 0, 0, 0.05);
--shadow-color: rgba(0, 0, 0, 0.1);
--map-land: #e5e7eb;
--map-border: #d1d5db;
--marker-inactive: #9ca3af;
}
[data-theme='dark'] {
--text-color: #f9fafb;
--text-secondary: #9ca3af;
--background-color: #111827;
--card-bg: #1f2937;
--input-bg: #374151;
--border-color: #374151;
--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;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.5;
transition: background-color 0.3s, color 0.3s;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.app-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
border-bottom: 1px solid var(--border-color);
background-color: var(--card-bg);
}
.app-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 1.5rem;
font-weight: 700;
}
.title-icon {
font-size: 1.75rem;
}
.app-main {
flex: 1;
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
width: 100%;
}
.app-description {
text-align: center;
color: var(--text-secondary);
margin-bottom: 1.5rem;
}
.app-footer {
text-align: center;
padding: 1rem;
border-top: 1px solid var(--border-color);
font-size: 0.85rem;
color: var(--text-secondary);
}
.app-footer .excellent { color: #22c55e; }
.app-footer .good { color: #eab308; }
.app-footer .poor { color: #ef4444; }
@media (max-width: 768px) {
.app-header {
padding: 1rem;
}
.app-title {
font-size: 1.25rem;
}
.app-main {
padding: 1rem;
}
}

1
src/client/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />