-
-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathNpmStatsChart.tsx
More file actions
91 lines (83 loc) · 1.91 KB
/
NpmStatsChart.tsx
File metadata and controls
91 lines (83 loc) · 1.91 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
import * as React from 'react'
import * as Plot from '@observablehq/plot'
import { ParentSize } from '@visx/responsive'
type NpmStats = {
start: string
end: string
package: string
downloads: Array<{
downloads: number
day: string
}>
}
export function NpmStatsChart({ stats }: { stats: NpmStats[] }) {
const plotRef = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
if (!stats.length || !plotRef.current) return
// Flatten the data for the plot
const plotData = stats.flatMap((stat) =>
stat.downloads.map((d) => ({
...d,
package: stat.package,
date: new Date(d.day),
})),
)
const chart = Plot.plot({
marginLeft: 50,
marginRight: 0,
marginBottom: 70,
width: plotRef.current.clientWidth,
height: plotRef.current.clientHeight,
marks: [
Plot.line(plotData, {
x: 'date',
y: 'downloads',
stroke: 'package',
strokeWidth: 2,
}),
],
x: {
type: 'time',
label: 'Date',
labelOffset: 35,
tickFormat: (d: Date) => d.toLocaleDateString(),
},
y: {
label: 'Downloads',
labelOffset: 35,
tickFormat: (d: number) => {
if (d >= 1000000) {
return `${(d / 1000000).toFixed(1)}M`
}
if (d >= 1000) {
return `${(d / 1000).toFixed(1)}K`
}
return d.toString()
},
},
grid: true,
color: {
legend: true,
},
})
plotRef.current.appendChild(chart)
return () => {
if (plotRef.current) {
plotRef.current.innerHTML = ''
}
}
}, [stats])
return (
<ParentSize>
{({ width, height }) => (
<div
ref={plotRef}
style={{
width,
height: Math.max(400, height * 0.6),
}}
/>
)}
</ParentSize>
)
}