43 lines
1.9 KiB
TypeScript
43 lines
1.9 KiB
TypeScript
import { Fragment } from "react"
|
|
|
|
interface SparklineProps {
|
|
data: Array<number | null | undefined>
|
|
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((value): value is number => typeof value === "number" && Number.isFinite(value))
|
|
if (!valid.length) return <span className="text-muted-foreground/50 text-xs font-mono" aria-label="Нет истории измерений">—</span>
|
|
|
|
const max = Math.max(...valid)
|
|
const min = Math.min(...valid)
|
|
const span = Math.max(1, max - min)
|
|
const segments: Array<Array<[number, number]>> = []
|
|
let segment: Array<[number, number]> = []
|
|
data.forEach((value, index) => {
|
|
if (typeof value !== "number" || !Number.isFinite(value)) { segment = []; return }
|
|
if (!segment.length) segments.push(segment)
|
|
segment.push([
|
|
data.length === 1 ? width / 2 : index / (data.length - 1) * width,
|
|
height - ((value - min) / span) * (height - 2) - 1,
|
|
])
|
|
})
|
|
|
|
return (
|
|
<svg role="img" aria-label="История измерений" width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: "block" }}>
|
|
{segments.map((points, index) => {
|
|
if (points.length === 1) return <circle key={index} cx={points[0][0]} cy={points[0][1]} r="1.5" fill={color} />
|
|
const line = points.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`).join(" ")
|
|
const area = `${line} L${points[points.length - 1][0]},${height} L${points[0][0]},${height} Z`
|
|
return <Fragment key={index}>
|
|
{filled && <path d={area} style={{ fill: color, fillOpacity: 0.15 }} />}
|
|
<path d={line} fill="none" style={{ stroke: color }} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
|
|
</Fragment>
|
|
})}
|
|
</svg>
|
|
)
|
|
}
|