-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathChartContainer.jsx
More file actions
664 lines (615 loc) · 21.2 KB
/
ChartContainer.jsx
File metadata and controls
664 lines (615 loc) · 21.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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
import {
CategoryScale,
Chart as ChartJS,
Legend,
LinearScale,
LineElement,
PointElement,
Title,
Tooltip,
} from 'chart.js';
import zoomPlugin from 'chartjs-plugin-zoom';
import {
ChevronLeft,
ChevronRight,
Expand,
MoveHorizontal,
SkipBack,
SkipForward,
ZoomIn,
ZoomOut,
} from 'lucide-react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Line } from 'react-chartjs-2';
import { fetchChartData } from '../api';
import { formatDate, stringToColor } from '../utils';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
zoomPlugin
);
// Custom tooltip positioner - 50px from cursor, 50px above nearest point
Tooltip.positioners.topCorner = function(elements, eventPosition) {
const chart = this.chart;
const chartCenter = (chart.chartArea.left + chart.chartArea.right) / 2;
const chartVerticalCenter = (chart.chartArea.top + chart.chartArea.bottom) / 2;
const isOnRightSide = eventPosition.x > chartCenter;
const isOnTopSide = eventPosition.y < chartVerticalCenter;
let x = isOnRightSide ? eventPosition.x - 150 : eventPosition.x + 150;
let y = isOnTopSide ? chart.chartArea.top + 100 : chart.chartArea.bottom - 100;
return {
x,
y,
xAlign: isOnRightSide ? 'right' : 'left',
yAlign: isOnTopSide ? 'top' : 'bottom',
};
};
const DEFAULT_RANGE_SIZE = 100;
export default function ChartContainer({
groupName,
chartName,
displayName,
unit,
config,
engineFilter,
onFullscreen,
}) {
const [totalCommits, setTotalCommits] = useState(null);
const [chartData, setChartData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// viewRange stores the requested range: either { last: N } or { startIdx, endIdx }
const [viewRange, setViewRange] = useState({ last: DEFAULT_RANGE_SIZE });
const chartRef = useRef(null);
const isResettingZoom = useRef(false);
// Fetch data for the current view range
useEffect(() => {
let cancelled = false;
async function loadData() {
setLoading(true);
setError(null);
try {
let options = {};
if (viewRange.last) {
// Initial load: get last N commits
options = { last: viewRange.last };
} else if (viewRange.startIdx !== undefined && viewRange.endIdx !== undefined) {
// Navigation: use index-based range
options = { startIdx: viewRange.startIdx, endIdx: viewRange.endIdx };
}
const data = await fetchChartData(groupName, chartName, options);
if (!cancelled && data) {
setChartData(data);
if (data.originalLength) {
setTotalCommits(data.originalLength);
} else if (data.commits) {
setTotalCommits(data.commits.length);
}
}
} catch (err) {
if (!cancelled) {
setError(err.message);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
}
loadData();
return () => {
cancelled = true;
};
}, [groupName, chartName, viewRange]);
// Compute display range info from chartData (for rendering only)
const displayRangeInfo = useMemo(() => {
if (!chartData) return { startIdx: 0, endIdx: 0, total: 0, rangeSize: 0 };
const total = chartData.originalLength || chartData.commits?.length || 0;
const rangeSize = chartData.commits?.length || 0;
const req = chartData.requestedRange || {};
const startIdx = req.startIndex ?? (total - rangeSize);
const endIdx = req.endIndex ?? (total - 1);
return { startIdx, endIdx, total, rangeSize };
}, [chartData]);
// Compute current range from viewRange state (for navigation calculations)
const getCurrentRange = useCallback(() => {
const total = totalCommits || 0;
if (viewRange.last) {
const rangeSize = Math.min(viewRange.last, total);
return {
startIdx: Math.max(0, total - rangeSize),
endIdx: total - 1,
total,
rangeSize,
};
}
const startIdx = viewRange.startIdx ?? 0;
const endIdx = viewRange.endIdx ?? (total - 1);
return {
startIdx,
endIdx,
total,
rangeSize: endIdx - startIdx + 1,
};
}, [viewRange, totalCommits]);
const isAtStart = displayRangeInfo.startIdx === 0;
const isAtEnd = displayRangeInfo.endIdx >= displayRangeInfo.total - 1;
const currentRangeSize = displayRangeInfo.rangeSize;
// Navigation handlers - use functional updates to get latest state
const handleGoToStart = useCallback(() => {
const range = getCurrentRange();
if (range.startIdx === 0 || !range.total) return;
setViewRange({
startIdx: 0,
endIdx: Math.min(range.rangeSize - 1, range.total - 1),
});
}, [getCurrentRange]);
const handleGoToEnd = useCallback(() => {
const range = getCurrentRange();
if (range.endIdx >= range.total - 1 || !range.total) return;
setViewRange({ last: range.rangeSize });
}, [getCurrentRange]);
const handleMoveBackward = useCallback(() => {
const range = getCurrentRange();
if (range.startIdx === 0 || !range.total) return;
const moveAmount = Math.max(1, Math.floor(range.rangeSize / 2));
const newStartIdx = Math.max(0, range.startIdx - moveAmount);
const newEndIdx = newStartIdx + range.rangeSize - 1;
setViewRange({
startIdx: newStartIdx,
endIdx: Math.min(newEndIdx, range.total - 1),
});
}, [getCurrentRange]);
const handleMoveForward = useCallback(() => {
const range = getCurrentRange();
if (range.endIdx >= range.total - 1 || !range.total) return;
const moveAmount = Math.max(1, Math.floor(range.rangeSize / 2));
const newEndIdx = Math.min(range.total - 1, range.endIdx + moveAmount);
const newStartIdx = Math.max(0, newEndIdx - range.rangeSize + 1);
setViewRange({ startIdx: newStartIdx, endIdx: newEndIdx });
}, [getCurrentRange]);
const handleZoomIn = useCallback(() => {
const range = getCurrentRange();
if (!range.total || range.rangeSize <= 10) return;
const center = Math.floor((range.startIdx + range.endIdx) / 2);
const newRangeSize = Math.max(10, Math.floor(range.rangeSize / 2));
const halfRange = Math.floor(newRangeSize / 2);
let newStartIdx = center - halfRange;
let newEndIdx = newStartIdx + newRangeSize - 1;
// Clamp to bounds
if (newStartIdx < 0) {
newStartIdx = 0;
newEndIdx = newRangeSize - 1;
}
if (newEndIdx >= range.total) {
newEndIdx = range.total - 1;
newStartIdx = Math.max(0, newEndIdx - newRangeSize + 1);
}
setViewRange({ startIdx: newStartIdx, endIdx: newEndIdx });
}, [getCurrentRange]);
const handleZoomOut = useCallback(() => {
const range = getCurrentRange();
if (!range.total) return;
const center = Math.floor((range.startIdx + range.endIdx) / 2);
const newRangeSize = Math.min(range.total, range.rangeSize * 2);
const halfRange = Math.floor(newRangeSize / 2);
let newStartIdx = center - halfRange;
let newEndIdx = newStartIdx + newRangeSize - 1;
// Clamp to bounds
if (newStartIdx < 0) {
newStartIdx = 0;
newEndIdx = Math.min(newRangeSize - 1, range.total - 1);
}
if (newEndIdx >= range.total) {
newEndIdx = range.total - 1;
newStartIdx = Math.max(0, newEndIdx - newRangeSize + 1);
}
setViewRange({ startIdx: newStartIdx, endIdx: newEndIdx });
}, [getCurrentRange]);
const handleShowFullRange = useCallback(() => {
const range = getCurrentRange();
if (!range.total) return;
setViewRange({ startIdx: 0, endIdx: range.total - 1 });
}, [getCurrentRange]);
const isFullRange = isAtStart && isAtEnd;
// Handle drag selection zoom
const handleDragZoom = useCallback((startDataIdx, endDataIdx) => {
if (!chartData?.commits || !chartData.requestedRange) return;
const numCommits = chartData.commits.length;
if (numCommits < 2) return;
const rangeStart = chartData.requestedRange.startIndex;
const rangeEnd = chartData.requestedRange.endIndex;
const total = chartData.originalLength || rangeEnd + 1;
// Map chart indices to original dataset indices using linear interpolation
// This correctly handles downsampled data where numCommits < (rangeEnd - rangeStart + 1)
const minIdx = Math.min(startDataIdx, endDataIdx);
const maxIdx = Math.max(startDataIdx, endDataIdx);
const globalStartIdx = rangeStart + Math.round(minIdx / (numCommits - 1) * (rangeEnd - rangeStart));
const globalEndIdx = rangeStart + Math.round(maxIdx / (numCommits - 1) * (rangeEnd - rangeStart));
// Ensure minimum range
if (globalEndIdx - globalStartIdx < 5) return;
setViewRange({
startIdx: Math.max(0, globalStartIdx),
endIdx: Math.min(total - 1, globalEndIdx),
});
}, [chartData]);
// Process series data with filters and renaming
const processedData = useMemo(() => {
if (!chartData?.series || !chartData?.commits) return null;
const { series, commits } = chartData;
const datasets = [];
const labels = commits.map(c => formatDate(c.timestamp));
Object.entries(series).forEach(([seriesName, points]) => {
// Apply removed datasets filter
if (config.removedDatasets?.has(seriesName)) return;
// Apply engine filter
if (engineFilter !== 'all') {
const engine = seriesName.split(':')[0].toLowerCase();
if (engine !== engineFilter && !seriesName.toLowerCase().includes(engineFilter)) {
return;
}
}
// Rename series if needed
let displaySeriesName = seriesName;
if (config.renamedDatasets) {
const caseInsensitive = {};
Object.entries(config.renamedDatasets).forEach(([k, v]) => {
caseInsensitive[k.toLowerCase()] = v;
});
displaySeriesName = caseInsensitive[seriesName.toLowerCase()] || seriesName;
}
// Check if hidden by default
const hidden = config.hiddenDatasets?.has(seriesName) ||
config.hiddenDatasets?.has(displaySeriesName);
datasets.push({
label: displaySeriesName,
data: points,
borderColor: stringToColor(displaySeriesName),
backgroundColor: stringToColor(displaySeriesName) + '20',
pointRadius: 2,
pointHoverRadius: 5,
pointStyle: 'cross',
borderWidth: 1.5,
tension: 0,
spanGaps: true,
hidden,
});
});
return { labels, datasets, commits };
}, [chartData, config, engineFilter]);
// Handle click on chart point to open commit on GitHub
const handleChartClick = useCallback((event, elements) => {
if (!elements.length || !processedData?.commits) return;
const dataIndex = elements[0].index;
const commit = processedData.commits[dataIndex];
if (commit?.id) {
window.open(`https://github.com/vortex-data/vortex/commit/${commit.id}`, '_blank');
}
}, [processedData]);
// Chart.js options with drag zoom
const options = useMemo(() => ({
responsive: true,
maintainAspectRatio: false,
animation: false,
onClick: handleChartClick,
onHover: (event, elements) => {
event.native.target.style.cursor = elements.length ? 'pointer' : 'default';
},
interaction: {
mode: 'index',
intersect: true,
},
plugins: {
legend: {
position: 'top',
align: 'start',
labels: {
boxWidth: 12,
padding: 8,
font: {
size: 12,
family: 'Geist, sans-serif',
},
usePointStyle: true,
pointStyle: 'rectRounded',
},
},
tooltip: {
backgroundColor: 'rgba(16, 16, 16, 0.9)',
titleFont: { family: 'Geist, sans-serif', size: 13 },
bodyFont: { family: 'Geist Mono, monospace', size: 12 },
padding: 12,
cornerRadius: 4,
position: 'topCorner',
caretSize: 0,
itemSort: (a, b) => b.parsed.y - a.parsed.y,
// Limit to top 10 items by value to prevent tooltip from getting too large
filter: (item, _index, items) => {
if (items.length <= 10) return item.parsed.y != null;
const validItems = items.filter(i => i.parsed.y != null);
if (validItems.length <= 10) return item.parsed.y != null;
const sorted = [...validItems].sort((a, b) => (b.parsed.y ?? 0) - (a.parsed.y ?? 0));
const top10 = sorted.slice(0, 10);
return top10.some(i => i.datasetIndex === item.datasetIndex);
},
callbacks: {
title: (items) => {
if (!items.length || !processedData?.commits) return '';
const commit = processedData.commits[items[0].dataIndex];
if (!commit) return items[0].label;
const author = commit.author || 'Unknown';
return `${formatDate(commit.timestamp)} — ${author}\n(${commit.id?.slice(0, 7) || ''}) ${commit.message || ''}`;
},
label: (item) => {
const value = item.parsed.y;
if (value == null) return null;
const formattedValue = value < 1 ? value.toFixed(4) : value.toFixed(2);
return `${item.dataset.label}: ${formattedValue} ${unit || ''}`;
},
labelTextColor: (tooltipItem) => {
const chart = tooltipItem.chart;
const activeElements = chart._active || [];
if (activeElements.length === 0) return '#ffffff';
const lastEvent = chart._lastEvent;
if (!lastEvent) return '#ffffff';
// Find which dataset point is closest to the cursor
let hoveredDatasetIndex = activeElements[0].datasetIndex;
let closestDist = Infinity;
for (const el of activeElements) {
const point = chart.getDatasetMeta(el.datasetIndex).data[el.index];
if (point) {
const dist = Math.hypot(point.x - lastEvent.x, point.y - lastEvent.y);
if (dist < closestDist) {
closestDist = dist;
hoveredDatasetIndex = el.datasetIndex;
}
}
}
if (tooltipItem.datasetIndex === hoveredDatasetIndex) {
return '#ffffff';
}
return 'rgba(255, 255, 255, 0.45)';
},
},
},
zoom: {
zoom: {
drag: {
enabled: true,
backgroundColor: 'rgba(99, 102, 241, 0.2)',
borderColor: 'rgba(99, 102, 241, 0.8)',
borderWidth: 1,
},
mode: 'x',
onZoomComplete: ({ chart }) => {
// Prevent infinite loop from resetZoom triggering onZoomComplete
if (isResettingZoom.current) {
isResettingZoom.current = false;
return;
}
const { min, max } = chart.scales.x;
const startIdx = Math.floor(min);
const endIdx = Math.ceil(max);
if (startIdx >= 0 && endIdx > startIdx) {
handleDragZoom(startIdx, endIdx);
}
// Reset chart zoom state
isResettingZoom.current = true;
chart.resetZoom();
},
},
},
},
scales: {
x: {
display: true,
grid: {
display: true,
color: 'rgba(166, 166, 166, 0.12)',
},
ticks: {
maxRotation: 45,
minRotation: 45,
font: {
size: 11,
family: 'Geist, sans-serif',
},
maxTicksLimit: 10,
callback: function(value, index, ticks) {
// Always show first and last tick
if (index === 0 || index === ticks.length - 1) {
return this.getLabelForValue(value);
}
// Show intermediate ticks based on maxTicksLimit
const step = Math.ceil(ticks.length / 10);
if (index % step === 0) {
return this.getLabelForValue(value);
}
return null;
},
},
},
y: {
display: true,
beginAtZero: true,
grid: {
color: 'rgba(166, 166, 166, 0.12)',
},
ticks: {
font: {
size: 12,
family: 'Geist Mono, monospace',
},
},
title: {
display: !!unit,
text: unit || '',
font: {
size: 12,
family: 'Geist, sans-serif',
},
},
},
},
}), [unit, processedData, handleDragZoom, handleChartClick]);
// Fullscreen handler
const handleFullscreen = useCallback(() => {
if (processedData) {
onFullscreen({
title: displayName,
groupName,
chartName,
unit,
config,
initialData: processedData,
totalCommits,
currentRange: getCurrentRange(),
});
}
}, [processedData, displayName, groupName, chartName, unit, config, totalCommits, getCurrentRange, onFullscreen]);
// Show placeholder only on initial load (no data yet)
const showPlaceholder = !processedData && (loading || error);
const showOverlay = loading && processedData;
if (showPlaceholder) {
return (
<div className="chart-container">
<div className="chart-header">
<span className="chart-title">{displayName}</span>
</div>
<div className="chart-canvas-placeholder">
{error ? (
<p style={{ color: 'var(--text-secondary)' }}>Error loading chart</p>
) : (
<div className="chart-loading-spinner" />
)}
</div>
</div>
);
}
if (!loading && error) {
return (
<div className="chart-container">
<div className="chart-header">
<span className="chart-title">{displayName}</span>
</div>
<div className="chart-canvas-placeholder">
<p style={{ color: 'var(--text-secondary)' }}>Error loading chart</p>
</div>
</div>
);
}
if (!processedData || processedData.datasets.length === 0) {
return (
<div className="chart-container">
<div className="chart-header">
<span className="chart-title">{displayName}</span>
</div>
<div className="chart-canvas-placeholder">
<p style={{ color: 'var(--text-secondary)' }}>No data available</p>
</div>
</div>
);
}
return (
<div className="chart-container">
<div className="chart-header">
<span className="chart-title">
{displayName}
{chartData?.downsampleLevel && chartData.downsampleLevel !== '1x' && (
<span className="downsample-indicator" title="Data is downsampled for performance">
{chartData.downsampleLevel} downsampled
</span>
)}
</span>
<div className="chart-actions">
<div className="chart-zoom-controls">
<button
className="chart-zoom-btn"
onClick={handleGoToStart}
disabled={loading || isAtStart}
data-tooltip="Go to beginning"
>
<SkipBack size={14} />
</button>
<button
className="chart-zoom-btn"
onClick={handleMoveBackward}
disabled={loading || isAtStart}
data-tooltip="Move backwards"
>
<ChevronLeft size={14} />
</button>
<button
className="chart-zoom-btn"
onClick={handleZoomOut}
disabled={loading || isFullRange}
data-tooltip="Zoom out"
>
<ZoomOut size={14} />
</button>
<button
className="chart-zoom-btn"
onClick={handleZoomIn}
disabled={loading || currentRangeSize <= 10}
data-tooltip="Zoom in"
>
<ZoomIn size={14} />
</button>
<button
className="chart-zoom-btn"
onClick={handleMoveForward}
disabled={loading || isAtEnd}
data-tooltip="Move forwards"
>
<ChevronRight size={14} />
</button>
<button
className="chart-zoom-btn"
onClick={handleGoToEnd}
disabled={loading || isAtEnd}
data-tooltip="Go to end"
>
<SkipForward size={14} />
</button>
<button
className="chart-zoom-btn"
onClick={handleShowFullRange}
disabled={loading || isFullRange}
data-tooltip="Show full range"
>
<MoveHorizontal size={14} />
</button>
</div>
<button
className="chart-zoom-btn"
onClick={handleFullscreen}
disabled={loading}
data-tooltip="Fullscreen"
>
<Expand size={14} />
</button>
</div>
</div>
<div className={`chart-canvas-wrapper ${showOverlay ? 'loading' : ''}`}>
<Line
ref={chartRef}
data={{
labels: processedData.labels,
datasets: processedData.datasets,
}}
options={options}
/>
{showOverlay && (
<div className="chart-loading-overlay">
<div className="chart-loading-spinner" />
</div>
)}
</div>
</div>
);
}