medkit/src/charts/sparkline.tsx

33 lines
1.3 KiB
TypeScript

import { useElementWidth } from "./chart-hover"
/** Мини-тренд для плитки: линия 2px и точка на последнем значении. */
export function Sparkline({
values,
height = 28,
color = "var(--chart-1)",
}: {
values: readonly (number | null)[]
height?: number
color?: string
}) {
const [ref, width] = useElementWidth<HTMLDivElement>()
const points = values.map((v, i) => ({ i, v })).filter((p): p is { i: number; v: number } => p.v !== null)
const min = Math.min(...points.map((p) => p.v))
const max = Math.max(...points.map((p) => p.v))
const x = (i: number) => 4 + (i / Math.max(1, values.length - 1)) * (width - 8)
const y = (v: number) => 4 + (max === min ? 0.5 : 1 - (v - min) / (max - min)) * (height - 8)
const d = points.map((p, k) => `${k ? "L" : "M"}${x(p.i).toFixed(1)},${y(p.v).toFixed(1)}`).join("")
const last = points.at(-1)
return (
<div ref={ref} style={{ height }} aria-hidden>
{width > 0 && points.length > 1 && (
<svg width={width} height={height} className="block overflow-visible">
<path d={d} fill="none" stroke={color} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" opacity={0.85} />
{last && <circle cx={x(last.i)} cy={y(last.v)} r={3.5} fill={color} stroke="var(--card)" strokeWidth={2} />}
</svg>
)}
</div>
)
}