forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScatterChart.tsx
More file actions
99 lines (89 loc) 路 2.65 KB
/
Copy pathScatterChart.tsx
File metadata and controls
99 lines (89 loc) 路 2.65 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
'use client';
import {
Chart as ChartJS,
LinearScale,
PointElement,
Tooltip,
Legend,
LineElement,
} from 'chart.js';
import { Scatter } from 'react-chartjs-2';
import { memo, useCallback, useState } from 'react';
import { useScatterDataQuery } from '@/lib/analytics-queries';
import { getScatterCategories } from '@/lib/analytics-data';
import { regression } from '@/lib/utils';
import ExportButton from '@/components/ui/ExportButton';
import { exportRowsToCsv } from '@/lib/export';
import ChartSkeleton from '@/components/ui/ChartSkeleton';
ChartJS.register(LinearScale, PointElement, Tooltip, Legend, LineElement);
const colors: Record<string, string> = {
Tech: 'blue',
Finance: 'green',
AI: 'purple',
Web3: 'orange',
};
function ScatterChart() {
const [category, setCategory] = useState<string | null>(null);
const { data, isLoading, error } = useScatterDataQuery();
const handleCategoryChange = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
setCategory(e.target.value || null);
}, []);
if (isLoading || !data) return <ChartSkeleton />;
if (error) return <p>Unable to load scatter plot.</p>;
const filtered = category ? data.filter((d) => d.category === category) : data;
const reg = regression(filtered);
const scatterData = {
datasets: [
{
label: 'Gists',
data: filtered.map((d) => ({ x: d.age, y: d.engagement })),
backgroundColor: filtered.map((d) => colors[d.category]),
},
{
label: 'Trendline',
data: [
{ x: 0, y: reg.intercept },
{ x: 365, y: reg.slope * 365 + reg.intercept },
],
borderColor: 'red',
borderWidth: 2,
pointRadius: 0,
showLine: true,
},
],
};
return (
<div>
<ExportButton
onExport={(onProgress) =>
exportRowsToCsv({
filenamePrefix: 'scatter-chart',
filters: { category: category ?? 'All' },
rows: filtered.map((gist) => ({
id: gist.id,
age_days: gist.age,
engagement: gist.engagement,
category: gist.category,
})),
onProgress,
})
}
/>
<select onChange={handleCategoryChange}>
<option value="">All</option>
{getScatterCategories().map((item) => (
<option key={item} value={item}>{item}</option>
))}
</select>
<Scatter
data={scatterData}
options={{
onClick: (_, elements) => {
if (elements.length) alert(`Gist: ${filtered[elements[0].index].id}`);
},
}}
/>
</div>
);
}
export default memo(ScatterChart);