-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathindex.jsx
More file actions
529 lines (482 loc) · 16.5 KB
/
index.jsx
File metadata and controls
529 lines (482 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
const React = require('react')
const { createRoot } = require('react-dom/client')
import * as speedtest from './lib/speed-test.js'
import * as history from './lib/history.js'
const sl = require('react-sparklines')
const { Sparklines, SparklinesLine } = sl
// Constants
const ICON_LOCATION = "https://cdn.statically.io/gh/hampusborgos/country-flags/main/svg/"
const RENDER_THROTTLE_MS = 100
// Global state
let globalBlockList = []
let lastRenderTime = 0
let globalStats = { requestsPerSecond: 0 }
let progressState = {
phase: 'warmup',
completed: 0,
total: 0,
percentage: 0,
isVisible: true
}
// Theme management
const getTheme = () => {
const saved = localStorage.getItem('theme')
if (saved) return saved
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark'
}
return 'light'
}
const setTheme = (theme) => {
localStorage.setItem('theme', theme)
document.documentElement.setAttribute('data-theme', theme)
}
// Record history
speedtest.on(history.record)
// Throttled rendering to prevent excessive DOM updates
speedtest.on(() => {
// Don't render main table during warm-up phase
if (progressState.isVisible) {
return
}
const now = Date.now()
if (now - lastRenderTime < RENDER_THROTTLE_MS) {
return // Skip this render to avoid excessive updates
}
lastRenderTime = now
// Update stats
globalStats = speedtest.getStats()
// Clear CSS cache before re-render to pick up theme changes
cssVariablesCache = null
const scrollPosition = window.scrollY
render(<Table history={history.read()} blockList={globalBlockList} stats={globalStats} />)
// Preserve scroll position after render
if (Math.abs(window.scrollY - scrollPosition) > 5) {
window.scrollTo(0, scrollPosition)
}
})
// Update blocklist
speedtest.onBlocklistUpdate(blockList => {
globalBlockList = blockList
})
// Track progress during warm-up phase
speedtest.onProgress(progress => {
progressState = { ...progress, isVisible: progress.phase === 'warmup' }
if (progress.phase === 'warmup') {
// Show progress during warm-up
const container = document.getElementById('content')
if (container) {
render(<ProgressIndicator progress={progressState} />)
}
} else if (progress.phase === 'testing') {
// Switch to main table when warm-up is complete
setTimeout(() => {
progressState.isVisible = false
render(<Table history={history.read()} blockList={globalBlockList} stats={globalStats} />)
}, 500) // Small delay to show completion
}
})
// Update stats periodically
setInterval(() => {
if (!progressState.isVisible) {
globalStats = speedtest.getStats()
// Trigger a render to update the stats display
const scrollPosition = window.scrollY
render(<Table history={history.read()} blockList={globalBlockList} stats={globalStats} />)
if (Math.abs(window.scrollY - scrollPosition) > 5) {
window.scrollTo(0, scrollPosition)
}
}
}, 1000) // Update every second
/**
* Render JSX to the content container
* @param {React.Element} jsx - The JSX element to render
*/
function render(jsx) {
try {
const container = document.getElementById('content')
if (!container) {
console.error('Content container not found')
return
}
if (!container._root) {
container.innerHTML = ''
container._root = createRoot(container)
}
container._root.render(jsx)
} catch (error) {
console.error('Render error:', error)
// Fallback to simple text if React rendering fails
const container = document.getElementById('content')
if (container) {
container.innerHTML = '<p>Error loading speed test. Please refresh the page.</p>'
}
}
}
/**
* Theme toggle button component
* @returns {React.Element} Theme toggle button
*/
const ThemeToggle = () => {
const [theme, setThemeState] = React.useState(getTheme())
const handleToggle = () => {
const current = getTheme()
const next = current === 'dark' ? 'light' : 'dark'
setTheme(next)
setThemeState(next)
// Clear CSS cache to pick up new theme colors
cssVariablesCache = null
}
return (
<button
className="theme-toggle"
onClick={handleToggle}
title={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`}
>
{theme === 'dark' ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.6">
<circle cx="12" cy="12" r="5"/>
<line x1="12" y1="1" x2="12" y2="3"/>
<line x1="12" y1="21" x2="12" y2="23"/>
<line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/>
<line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
<line x1="1" y1="12" x2="3" y2="12"/>
<line x1="21" y1="12" x2="23" y2="12"/>
<line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/>
<line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.6">
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
</svg>
)}
</button>
)
}
/**
* Pause toggle button component
* @returns {React.Element} Pause toggle button
*/
const PauseToggle = () => {
const [paused, setPaused] = React.useState(speedtest.isPaused())
React.useEffect(() => {
// Listen for pause state changes
const unsubscribe = speedtest.onPauseChange(setPaused)
return unsubscribe // Cleanup on unmount
}, [])
const handleToggle = () => {
if (paused) {
speedtest.resume()
} else {
speedtest.pause()
}
}
return (
<button
className="pause-toggle"
onClick={handleToggle}
title={paused ? 'Resume testing' : 'Pause testing'}
aria-label={paused ? 'Resume testing' : 'Pause testing'}
>
{paused ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.6">
<polygon points="5 3 19 12 5 21 5 3"/>
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.6">
<rect x="6" y="4" width="4" height="16"/>
<rect x="14" y="4" width="4" height="16"/>
</svg>
)}
</button>
)
}
/**
* Progress indicator component for warm-up phase
* @param {Object} props - Component props
* @param {Object} props.progress - Progress state object
* @returns {React.Element} Progress indicator
*/
const ProgressIndicator = ({ progress }) => {
const { completed, total, percentage, phase } = progress
return (
<div>
<ThemeToggle />
<PauseToggle />
<div className="text-center mt-5">
<div className="mb-4">
<div className="spinner-border text-primary mb-3" role="status">
<span className="sr-only">Loading...</span>
</div>
<h4>Initializing Azure Speed Test</h4>
<p className="text-muted">
{phase === 'warmup' ?
'Warming up connections to all Azure regions...' :
'Starting latency measurements...'
}
</p>
</div>
<div className="progress mx-auto" style={{ maxWidth: '400px', height: '8px' }}>
<div
className="progress-bar progress-bar-striped progress-bar-animated"
role="progressbar"
style={{ width: `${percentage}%` }}
aria-valuenow={percentage}
aria-valuemin="0"
aria-valuemax="100"
></div>
</div>
<div className="mt-2">
<small className="text-muted">
{completed} of {total} regions initialized ({percentage}%)
</small>
</div>
{phase === 'warmup' && (
<div className="mt-3">
<small className="text-info">
<i className="fas fa-info-circle"></i> First ping to each region includes DNS lookup and is discarded for accuracy
</small>
</div>
)}
</div>
</div>
)
}
/**
* Render flag icon for a location
* @param {Object} item - Location item with icon property
* @returns {React.Element|string} Flag image or empty string
*/
const renderFlag = (item) => {
if (!item.icon) return ''
return (
<img
src={ICON_LOCATION + item.icon}
className="icon"
alt={`${item.name} flag`}
loading="lazy"
/>
)
}
/**
* Get CSS variable values (cached per render cycle)
*/
let cssVariablesCache = null
const getCSSVariables = () => {
if (!cssVariablesCache) {
const styles = getComputedStyle(document.documentElement)
cssVariablesCache = {
gradientColor: styles.getPropertyValue('--row-gradient-color').trim(),
bgColor: styles.getPropertyValue('--table-bg').trim(),
sparklineColor: styles.getPropertyValue('--sparkline-color').trim()
}
}
return cssVariablesCache
}
/**
* Render a data row for active locations
* @param {Object} item - Location data with latency information
* @returns {React.Element} Table row element
*/
const renderRow = (item) => {
const percentage = Math.min(Math.round(item.percent || 0), 100)
const { gradientColor, bgColor, sparklineColor } = getCSSVariables()
const rowStyle = {
backgroundImage: `linear-gradient(to right, ${gradientColor} ${percentage}%, ${bgColor} ${percentage}%)`
}
return (
<tr key={item.name} style={rowStyle}>
<td>
{renderFlag(item)}
{item.name}
{item.location && (
<small className="text-muted" style={{ marginLeft: '8px' }}>
{item.location}
{item.availabilityZones && (
<span className="badge badge-light" style={{ marginLeft: '6px', fontSize: '0.7em' }}>
AZ
</span>
)}
</small>
)}
</td>
<td>
{Math.round(item.average)}ms
</td>
<td style={{ padding: 0 }} className="no-mobile">
{item.values && item.values.length > 0 && (
<Sparklines
data={item.values}
width={200}
height={48}
limit={100}
margin={2}
>
<SparklinesLine
color={sparklineColor}
style={{ strokeWidth: 2 }}
/>
</Sparklines>
)}
</td>
</tr>
)
}
/**
* Render error row for blocked locations
* @param {Object} item - Blocked location data
* @returns {React.Element} Error table row
*/
const renderError = (item, historyData) => {
const handleRetry = (e) => {
e.preventDefault()
try {
speedtest.retry(item.domain)
} catch (error) {
console.error('Retry failed:', error)
}
}
const { sparklineColor } = getCSSVariables()
return (
<tr key={item.name} className="blocked-row">
<td>
{renderFlag(item)}
{item.name}
{item.location && (
<small className="text-muted" style={{ marginLeft: '8px' }}>
{item.location}
{item.availabilityZones && (
<span className="badge badge-light" style={{ marginLeft: '6px', fontSize: '0.7em' }}>
AZ
</span>
)}
</small>
)}
</td>
<td>
<span className="badge badge-danger">NO RESPONSE</span>
{historyData && historyData.average > 0 && (
<small className="text-muted" style={{ marginLeft: '8px' }}>
was {Math.round(historyData.average)}ms
</small>
)}
{' '}
<button
type="button"
className="btn btn-sm btn-outline-primary"
onClick={handleRetry}
title={`Retry ${item.name}`}
style={{ marginLeft: '8px' }}
>
Retry
</button>
</td>
<td style={{ padding: 0 }} className="no-mobile">
{historyData && historyData.values && historyData.values.length > 0 && (
<Sparklines
data={historyData.values}
width={200}
height={48}
limit={100}
margin={2}
>
<SparklinesLine
color={sparklineColor}
style={{ strokeWidth: 2, opacity: 0.5 }}
/>
</Sparklines>
)}
</td>
</tr>
)
}
/**
* Main table component displaying latency results
* @param {Object} props - Component props
* @param {Array} props.history - Array of location latency data
* @param {Array} props.blockList - Array of blocked/failed locations
* @param {Object} props.stats - Statistics object with request metrics
* @returns {React.Element} Complete results table
*/
const Table = ({ history = [], blockList = [], stats = {} }) => {
// Build lookup of history data by domain for blocked items
const historyByDomain = {}
history.forEach(h => { historyByDomain[h.domain] = h })
// Sort history by average latency for better UX
const sortedHistory = [...history].sort((a, b) => (a.average || Infinity) - (b.average || Infinity))
return (
<div>
<ThemeToggle />
<PauseToggle />
<div className="mb-3">
<small className="text-muted">
Testing {history.length + blockList.length} Azure regions | {' '}
{history.length} responding | {' '}
{blockList.length} not responding | {' '}
{stats.requestsPerSecond ? Math.round(stats.requestsPerSecond) : '0'} req/sec
{' | '}
<span className="badge badge-light" style={{ fontSize: '0.8em' }}>AZ</span> = Availability Zones Supported
</small>
</div>
<table className="table results-table table-hover">
<thead className="thead-light">
<tr>
<th scope="col">Data Center</th>
<th scope="col">Average Latency</th>
<th scope="col" className="no-mobile">History</th>
</tr>
</thead>
<tbody>
{sortedHistory.map(renderRow)}
{blockList.map(item => renderError(item, historyByDomain[item.domain]))}
</tbody>
</table>
<footer className="mt-5">
<div className="row">
<div className="col-md-6">
<h6>About</h6>
<p>
<a href="https://github.com/richorama/AzureSpeedTest2" target="_blank" rel="noopener noreferrer">
Fork on GitHub
</a>
</p>
<p>
Created by <a href="https://www.twitter.com/richorama/" target="_blank" rel="noopener noreferrer">@richorama</a>
</p>
</div>
<div className="col-md-6">
<h6>Contributors</h6>
<ul className="list-unstyled">
<li><a href="https://github.com/TimNilimaa" target="_blank" rel="noopener noreferrer">Tim Nilimaa</a> - Regional contributions and code improvements</li>
<li><a href="https://github.com/ncareau" target="_blank" rel="noopener noreferrer">NMC</a> - Canada storage accounts</li>
<li><a href="https://github.com/jurajsucik" target="_blank" rel="noopener noreferrer">Juraj Sucik</a> - Switzerland and Germany accounts</li>
<li><a href="https://github.com/wi5nia" target="_blank" rel="noopener noreferrer">Tomasz Wisniewski</a> - Poland Central account</li>
<li><a href="https://github.com/JanuszNowak" target="_blank" rel="noopener noreferrer">Janusz Nowak</a> - Denmark East account</li>
</ul>
</div>
</div>
<hr />
<div className="row">
<div className="col-12">
<h6>Resources</h6>
<p>
Visit the <a href="https://azure.microsoft.com/en-us/regions/" target="_blank" rel="noopener noreferrer">Azure regions page</a> for
a map of all data centers and the <a href="https://azure.microsoft.com/en-us/regions/services/" target="_blank" rel="noopener noreferrer">feature matrix</a>.
</p>
<p>
Missing a data center? See <a href="https://github.com/richorama/AzureSpeedTest2/issues/12" target="_blank" rel="noopener noreferrer">this issue</a> for more information.
</p>
<div className="alert alert-info" role="alert">
<small>
<strong>Disclaimer:</strong> The latency times are indicative only and do not represent
the maximum performance achievable from Microsoft Azure. Use this website purely as a tool
to gauge which Azure Data Center could be the best for your location.
</small>
</div>
</div>
</div>
</footer>
</div>
)
}