forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComparisonChart.tsx
More file actions
443 lines (411 loc) · 13.2 KB
/
Copy pathComparisonChart.tsx
File metadata and controls
443 lines (411 loc) · 13.2 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
// src/components/charts/ComparisonChart.tsx
//
// Functions: getValue, buildAverageSeries, buildComparisonOption, ComparisonChart
"use client"
import type { EChartsOption } from "echarts"
import { useState } from "react"
import { TabBar } from "@/components/ui/TabBar"
import { Tooltip } from "@/components/ui/Tooltip"
import { hexToRgba } from "@/lib/color-utils"
import { bytesToGiB } from "@/lib/formatters"
import type { Snapshot } from "@/types/api"
import type { FleetChartProps, TrackerSnapshotSeries } from "@/types/charts"
import { ChartECharts } from "./lib/ChartECharts"
import { ChartEmptyState } from "./lib/ChartEmptyState"
import {
adaptiveDotSize,
autoByteScale,
buildAxisPointer,
buildTimeXAxis,
fmtNum,
insideZoom,
yAxisAutoRange,
} from "./lib/chart-helpers"
import {
buildTimeSeriesData,
carryForwardTimeSeries,
collectUnifiedTimestamps,
} from "./lib/chart-transforms"
import { LogScaleToggle } from "./lib/LogScaleToggle"
import {
CHART_THEME,
chartAxisLabel,
chartGrid,
chartLegend,
chartTooltip,
chartTooltipHeader,
chartTooltipRow,
formatChartTimestamp,
} from "./lib/theme"
import { useLogScale } from "./lib/useLogScale"
type ChartMetric = "uploaded" | "downloaded" | "ratio" | "buffer" | "seedbonus" | "active"
const METRIC_COLOR: Record<ChartMetric, string> = {
uploaded: CHART_THEME.upload,
downloaded: CHART_THEME.download,
ratio: CHART_THEME.positive,
buffer: CHART_THEME.upload,
seedbonus: CHART_THEME.accent,
active: CHART_THEME.accent,
}
const METRIC_DIM: Record<ChartMetric, string> = {
uploaded: CHART_THEME.accentDim,
downloaded: CHART_THEME.warnDim,
ratio: hexToRgba(CHART_THEME.positive, 0.15),
buffer: CHART_THEME.accentDim,
seedbonus: CHART_THEME.accentDim,
active: CHART_THEME.accentDim,
}
interface ComparisonChartProps extends FleetChartProps {
metric: ChartMetric
enableLogScale?: boolean
enableAverage?: boolean
enableStacked?: boolean
}
function getValue(snapshot: Snapshot, metric: ChartMetric): number | null {
switch (metric) {
case "uploaded":
return bytesToGiB(snapshot.uploadedBytes)
case "downloaded":
return bytesToGiB(snapshot.downloadedBytes)
case "ratio":
return snapshot.ratio
case "buffer":
return bytesToGiB(snapshot.bufferBytes)
case "seedbonus":
return snapshot.seedbonus
case "active":
return snapshot.seedingCount
}
}
/** Compute a single "Avg" series, mean of all tracker values at each unified timestamp. */
function buildAverageSeries(
trackerData: TrackerSnapshotSeries[],
allTimestamps: number[],
metric: ChartMetric,
divisor: number,
dotSize: number,
useLog = false
): EChartsOption["series"] {
// Index each tracker's snapshots by ms timestamp
const trackerMaps = trackerData.map((tracker) => {
const m = new Map<number, Snapshot>()
for (const snap of tracker.snapshots) {
m.set(new Date(snap.polledAt).getTime(), snap)
}
return m
})
const data: [number, number][] = []
for (const ts of allTimestamps) {
const values: number[] = []
for (const snapByTs of trackerMaps) {
const snap = snapByTs.get(ts)
if (!snap) continue
const raw = getValue(snap, metric)
if (raw !== null) values.push(raw / divisor)
}
if (values.length === 0) continue
const avg = values.reduce((a, b) => a + b, 0) / values.length
if (useLog && avg <= 0) continue
data.push([ts, Number(avg.toFixed(3))])
}
const color = METRIC_COLOR[metric]
const dim = METRIC_DIM[metric]
return [
{
name: "Average",
type: "line",
sampling: "lttb",
data,
smooth: true,
symbol: "circle",
symbolSize: dotSize,
itemStyle: { color },
lineStyle: {
color,
width: 3,
shadowColor: color,
shadowBlur: 12,
},
emphasis: {
lineStyle: { shadowBlur: 20, shadowColor: color },
},
areaStyle: {
color: {
type: "linear",
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: dim },
{ offset: 1, color: hexToRgba(color, 0) },
],
} as unknown as string,
},
},
]
}
function buildComparisonOption(
metric: ChartMetric,
trackerData: TrackerSnapshotSeries[],
opts?: { logScale?: boolean; averageMode?: boolean; stacked?: boolean; totalOnly?: boolean }
): EChartsOption {
const useLog = opts?.logScale ?? false
const useAvg = opts?.averageMode ?? false
const useStacked = opts?.stacked ?? false
const useTotalOnly = opts?.totalOnly ?? false
// Collect unified ms timestamps from the union of all polledAt values
const allTimestamps = collectUnifiedTimestamps(trackerData)
// Determine unit and divisor per metric type
let unit = "x"
let divisor = 1
if (metric === "seedbonus") {
unit = "pts"
} else if (metric === "active") {
unit = "torrents"
} else if (metric !== "ratio") {
const allGiB: number[] = []
for (const tracker of trackerData) {
for (const snap of tracker.snapshots) {
const v = getValue(snap, metric)
if (v !== null) allGiB.push(v)
}
}
const maxGiB = Math.max(...allGiB, 0)
;({ divisor, unit } = autoByteScale(maxGiB))
}
const dotSize = adaptiveDotSize(allTimestamps.length)
// Build series either per-tracker or single average line
let series: EChartsOption["series"]
if (useTotalOnly) {
// Carry-forward each tracker onto the unified time axis, then sum at each timestamp
const perTracker = trackerData.map((tracker) =>
carryForwardTimeSeries(allTimestamps, tracker.snapshots, (s) => {
const raw = getValue(s, metric)
return raw !== null ? raw / divisor : null
})
)
// Build a map of ts -> sum across all trackers
const sumByTs = new Map<number, number>()
for (const series of perTracker) {
for (const [ts, val] of series) {
sumByTs.set(ts, (sumByTs.get(ts) ?? 0) + val)
}
}
const data: [number, number][] = [...sumByTs.entries()]
.sort(([a], [b]) => a - b)
.map(([ts, sum]) => [ts, Number(sum.toFixed(3))])
const totalColor = METRIC_COLOR[metric]
const totalDim = METRIC_DIM[metric]
series = [
{
name: "Fleet Total",
type: "line",
sampling: "lttb",
data,
smooth: true,
symbol: "circle",
symbolSize: dotSize,
areaStyle: {
color: {
type: "linear",
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: totalDim },
{ offset: 1, color: hexToRgba(totalColor, 0) },
],
} as unknown as string,
},
itemStyle: { color: totalColor },
lineStyle: {
color: totalColor,
width: 3,
shadowColor: totalColor,
shadowBlur: 12,
},
emphasis: {
lineStyle: { shadowBlur: 20, shadowColor: totalColor },
},
},
]
} else if (useAvg) {
series = buildAverageSeries(trackerData, allTimestamps, metric, divisor, dotSize, useLog)
} else {
series = trackerData.map((tracker) => {
const fieldFn = (s: Snapshot): number | null => {
const raw = getValue(s, metric)
if (raw === null) return null
const scaled = raw / divisor
if (useLog && scaled <= 0) return null
return Number(scaled.toFixed(3))
}
// For stacked mode, carry forward the last known value to avoid spike artifacts.
// For line mode, use sparse [ts, value][] pairs: time axis handles gaps natively.
let data: [number, number][]
if (useStacked) {
data = carryForwardTimeSeries(allTimestamps, tracker.snapshots, fieldFn)
} else {
data = buildTimeSeriesData(tracker.snapshots, fieldFn)
}
return {
name: tracker.name,
type: "line",
sampling: "lttb",
data,
smooth: true,
symbol: useStacked ? "none" : "circle",
symbolSize: dotSize,
...(useStacked ? { stack: "total", areaStyle: { opacity: 0.7 }, step: false } : {}),
itemStyle: { color: tracker.color },
lineStyle: {
color: tracker.color,
width: useStacked ? 1 : 2,
...(useStacked ? {} : { shadowColor: tracker.color, shadowBlur: 8 }),
},
emphasis: useStacked
? { focus: "series" as const }
: { focus: "series" as const, lineStyle: { shadowBlur: 16, shadowColor: tracker.color } },
}
})
}
// yAxis config — shared base with log/linear specifics
const yAxis: EChartsOption["yAxis"] = {
type: useLog ? "log" : "value",
name: unit,
...(useLog ? { logBase: 10 } : { scale: true, ...yAxisAutoRange() }),
nameTextStyle: {
color: CHART_THEME.textTertiary,
fontFamily: CHART_THEME.fontMono,
fontSize: CHART_THEME.fontSizeCompact,
},
axisLine: { show: false },
axisTick: { show: false },
axisLabel: chartAxisLabel({
formatter: (val: number) => fmtNum(val, 1),
}),
splitLine: {
lineStyle: { color: CHART_THEME.gridLine, width: 1 },
},
}
return {
backgroundColor: "transparent",
grid: chartGrid({ right: 16, left: 64 }),
tooltip: chartTooltip("axis", {
axisPointer: buildAxisPointer(CHART_THEME.borderMid, 0.8, 1),
formatter: (params: unknown) => {
const items = params as Array<{
seriesName: string
value: [number, number]
color: string
}>
if (!items || items.length === 0) return ""
const time = formatChartTimestamp(items[0].value[0])
const rows = items
.filter((item) => item.value != null && item.value[1] != null)
.map((item) => {
const val = item.value[1]
const display = metric === "ratio" ? `${fmtNum(val)} x` : `${fmtNum(val)} ${unit}`
return chartTooltipRow(item.color, item.seriesName, display)
})
.join("<br/>")
return chartTooltipHeader(time) + rows
},
}),
legend: useAvg || useTotalOnly ? { show: false } : chartLegend(),
xAxis: buildTimeXAxis(),
yAxis,
dataZoom: insideZoom(Math.max(...trackerData.map((t) => t.snapshots.length), 0)),
series,
}
}
function ComparisonChart({
metric,
trackerData,
height = 500,
enableLogScale = false,
enableAverage = false,
enableStacked = false,
}: ComparisonChartProps) {
const [averageMode, setAverageMode] = useState(false)
const [viewMode, setViewMode] = useState<"lines" | "stacked" | "total">("lines")
const hasData = trackerData.some((t) => t.snapshots.length > 0)
// Collect values for log scale detection
const allValues: number[] = []
if (enableLogScale) {
for (const tracker of trackerData) {
for (const snap of tracker.snapshots) {
const v = getValue(snap, metric)
if (v !== null) allValues.push(v)
}
}
}
const logScale = useLogScale(enableLogScale ? allValues : [])
const effectiveLog = enableLogScale ? logScale.effectiveLog : false
const isStacked = viewMode === "stacked"
const isTotalOnly = viewMode === "total"
const isNonLineMode = isStacked || isTotalOnly
const showToolbar = enableLogScale || enableAverage || enableStacked
if (!hasData) {
return (
<ChartEmptyState height={height} message="No snapshot data yet. Waiting for first polls..." />
)
}
const viewModes = enableStacked ? (["lines", "stacked", "total"] as const) : ([] as const)
return (
<div className="flex flex-col gap-2">
{showToolbar && (
<div className="flex justify-end gap-2">
{enableAverage && !isNonLineMode && (
<Tooltip
content={
averageMode
? "Showing fleet average. Click for per-tracker."
: "Showing per-tracker. Click for fleet average."
}
>
<button
type="button"
onClick={() => setAverageMode((v) => !v)}
className="timestamp nm-interactive-sm bg-raised px-2.5 py-1 hover:text-secondary cursor-pointer flex items-center gap-2 rounded-nm-sm"
>
{averageMode ? "Avg" : "Per-Tracker"}
</button>
</Tooltip>
)}
{enableLogScale && (
<LogScaleToggle
effectiveLog={logScale.effectiveLog}
isAuto={logScale.isAuto}
onToggle={logScale.onToggle}
/>
)}
{viewModes.length > 0 && !averageMode && (
<TabBar
compact
tabs={viewModes.map((m) => ({
key: m,
label: { lines: "Per-Tracker", stacked: "Stacked", total: "Total" }[m],
}))}
activeTab={viewMode}
onChange={setViewMode}
/>
)}
</div>
)}
<ChartECharts
option={buildComparisonOption(metric, trackerData, {
logScale: enableLogScale ? effectiveLog : undefined,
averageMode: averageMode && !isNonLineMode,
stacked: isStacked,
totalOnly: isTotalOnly,
})}
style={{ height, width: "100%" }}
/>
</div>
)
}
export type { ChartMetric, ComparisonChartProps }
export { buildComparisonOption, ComparisonChart }