32 lines
1.1 KiB
TypeScript
32 lines
1.1 KiB
TypeScript
interface SparklineProps {
|
|
data: number[]
|
|
width?: number
|
|
height?: number
|
|
color?: string
|
|
filled?: boolean
|
|
}
|
|
|
|
export function Sparkline({ data, width = 120, height = 28, color = "currentColor", filled = false }: SparklineProps) {
|
|
const valid = data.filter((v) => v != null && isFinite(v))
|
|
if (valid.length < 2) return <span className="text-muted-foreground/50 text-xs font-mono">—</span>
|
|
|
|
const max = Math.max(...valid)
|
|
const min = Math.min(...valid)
|
|
const span = Math.max(1, max - min)
|
|
|
|
const pts = data.map((v, i) => [
|
|
(i / (data.length - 1)) * width,
|
|
height - ((v - min) / span) * (height - 2) - 1,
|
|
])
|
|
|
|
const lineD = pts.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`).join(" ")
|
|
const areaD = `${lineD} L${width},${height} L0,${height} Z`
|
|
|
|
return (
|
|
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: "block" }}>
|
|
{filled && <path d={areaD} style={{ fill: color, fillOpacity: 0.15 }} />}
|
|
<path d={lineD} fill="none" style={{ stroke: color }} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
|
|
</svg>
|
|
)
|
|
}
|