Sparkline.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import { useId, useMemo } from 'react';
  2. import {
  3. Area,
  4. AreaChart,
  5. CartesianGrid,
  6. ReferenceDot,
  7. ReferenceLine,
  8. ResponsiveContainer,
  9. Tooltip,
  10. XAxis,
  11. YAxis,
  12. } from 'recharts';
  13. import './Sparkline.css';
  14. export interface SparklineReferenceLine {
  15. y: number;
  16. label?: string;
  17. color?: string;
  18. dash?: string;
  19. }
  20. export interface SparklineExtrema {
  21. show?: boolean;
  22. formatter?: (v: number) => string;
  23. minColor?: string;
  24. maxColor?: string;
  25. }
  26. const DEFAULT_MIN_COLOR = '#52c41a';
  27. const DEFAULT_MAX_COLOR = '#fa541c';
  28. interface SparklineProps {
  29. data: number[];
  30. data2?: number[];
  31. data3?: number[];
  32. stroke2?: string;
  33. stroke3?: string;
  34. name1?: string;
  35. name2?: string;
  36. name3?: string;
  37. labels?: (string | number)[];
  38. height?: number;
  39. stroke?: string;
  40. strokeWidth?: number;
  41. maxPoints?: number;
  42. showGrid?: boolean;
  43. fillOpacity?: number;
  44. showMarker?: boolean;
  45. markerRadius?: number;
  46. showAxes?: boolean;
  47. yTickStep?: number;
  48. tickCountX?: number;
  49. showTooltip?: boolean;
  50. valueMin?: number;
  51. valueMax?: number | null;
  52. yFormatter?: (v: number) => string;
  53. tooltipFormatter?: ((v: number) => string) | null;
  54. tooltipLabelFormatter?: ((label: string) => string) | null;
  55. referenceLines?: SparklineReferenceLine[];
  56. extrema?: SparklineExtrema;
  57. }
  58. interface ChartPoint {
  59. index: number;
  60. value: number;
  61. value2: number;
  62. value3: number;
  63. label: string;
  64. }
  65. export default function Sparkline({
  66. data,
  67. data2 = [],
  68. data3 = [],
  69. stroke2 = '#722ed1',
  70. stroke3 = '#a0d911',
  71. name1,
  72. name2,
  73. name3,
  74. labels = [],
  75. height = 80,
  76. stroke = '#008771',
  77. strokeWidth = 2,
  78. maxPoints = 120,
  79. showGrid = true,
  80. fillOpacity = 0.22,
  81. showMarker = true,
  82. markerRadius = 3,
  83. showAxes = false,
  84. yTickStep = 25,
  85. tickCountX = 4,
  86. showTooltip = false,
  87. valueMin = 0,
  88. valueMax = 100,
  89. yFormatter = (v: number) => `${Math.round(v)}%`,
  90. tooltipFormatter = null,
  91. tooltipLabelFormatter = null,
  92. referenceLines,
  93. extrema,
  94. }: SparklineProps) {
  95. const reactId = useId();
  96. const safeId = reactId.replace(/[^a-zA-Z0-9]/g, '');
  97. const gradId = `spkGrad-${safeId}`;
  98. const gradId2 = `spkGrad2-${safeId}`;
  99. const gradId3 = `spkGrad3-${safeId}`;
  100. const hasSeries2 = data2.length > 0;
  101. const hasSeries3 = data3.length > 0;
  102. const multiSeries = hasSeries2 || hasSeries3;
  103. const points = useMemo<ChartPoint[]>(() => {
  104. const n = Math.min(data.length, maxPoints);
  105. if (n === 0) return [];
  106. const sliceStart = data.length - n;
  107. const labelStart = Math.max(0, labels.length - n);
  108. const slice2Start = data2.length - n;
  109. const slice3Start = data3.length - n;
  110. return data.slice(sliceStart).map((value, i) => ({
  111. index: i,
  112. value: Number(value) || 0,
  113. value2: data2.length ? Number(data2[slice2Start + i]) || 0 : 0,
  114. value3: data3.length ? Number(data3[slice3Start + i]) || 0 : 0,
  115. label: String(labels[labelStart + i] ?? i + 1),
  116. }));
  117. }, [data, data2, data3, labels, maxPoints]);
  118. const yDomain = useMemo<[number, number]>(() => {
  119. if (valueMax != null) return [valueMin, valueMax];
  120. let max = valueMin;
  121. for (const p of points) {
  122. if (Number.isFinite(p.value) && p.value > max) max = p.value;
  123. if (hasSeries2 && Number.isFinite(p.value2) && p.value2 > max) max = p.value2;
  124. if (hasSeries3 && Number.isFinite(p.value3) && p.value3 > max) max = p.value3;
  125. }
  126. if (max <= valueMin) max = valueMin + 1;
  127. return [valueMin, max * 1.1];
  128. }, [points, valueMin, valueMax, hasSeries2, hasSeries3]);
  129. const yTicks = useMemo(() => {
  130. if (!showAxes) return undefined;
  131. const [min, max] = yDomain;
  132. if (valueMax === 100 && valueMin === 0 && yTickStep > 0) {
  133. const out: number[] = [];
  134. for (let v = min; v <= max; v += yTickStep) out.push(v);
  135. return out;
  136. }
  137. const n = 5;
  138. return Array.from({ length: n }, (_, i) => min + ((max - min) * i) / (n - 1));
  139. }, [showAxes, yDomain, valueMin, valueMax, yTickStep]);
  140. const xTickIndexes = useMemo(() => {
  141. if (!showAxes || points.length === 0) return undefined;
  142. const m = Math.max(2, tickCountX);
  143. return Array.from({ length: m }, (_, i) => Math.round((i * (points.length - 1)) / (m - 1)));
  144. }, [showAxes, tickCountX, points.length]);
  145. const fmtTooltip = tooltipFormatter ?? yFormatter;
  146. const extremaPoints = useMemo(() => {
  147. if (!extrema?.show || multiSeries || points.length < 2) return null;
  148. let minIdx = 0;
  149. let maxIdx = 0;
  150. for (let i = 1; i < points.length; i++) {
  151. if (points[i].value < points[minIdx].value) minIdx = i;
  152. if (points[i].value > points[maxIdx].value) maxIdx = i;
  153. }
  154. if (minIdx === maxIdx) return null;
  155. return { min: points[minIdx], max: points[maxIdx], minIdx, maxIdx };
  156. }, [points, extrema?.show, multiSeries]);
  157. const legendItems = useMemo(
  158. () =>
  159. [
  160. { name: name1, color: stroke },
  161. { name: name2, color: stroke2 },
  162. { name: name3, color: stroke3 },
  163. ].filter((s, i) => s.name && (i === 0 ? multiSeries : i === 1 ? hasSeries2 : hasSeries3)),
  164. [name1, name2, name3, stroke, stroke2, stroke3, multiSeries, hasSeries2, hasSeries3],
  165. );
  166. const fmtExtrema = extrema?.formatter ?? yFormatter;
  167. const minColor = extrema?.minColor ?? DEFAULT_MIN_COLOR;
  168. const maxColor = extrema?.maxColor ?? DEFAULT_MAX_COLOR;
  169. const ariaSummary = useMemo(() => {
  170. if (points.length === 0) return name1 ?? '';
  171. const last = points[points.length - 1];
  172. const parts: string[] = [];
  173. parts.push(name1 ? `${name1}: ${yFormatter(last.value)}` : yFormatter(last.value));
  174. if (hasSeries2 && name2) parts.push(`${name2}: ${yFormatter(last.value2)}`);
  175. if (hasSeries3 && name3) parts.push(`${name3}: ${yFormatter(last.value3)}`);
  176. return parts.join(', ');
  177. }, [points, name1, name2, name3, hasSeries2, hasSeries3, yFormatter]);
  178. return (
  179. <div className="sparkline-container" role={ariaSummary ? 'img' : undefined} aria-label={ariaSummary || undefined}>
  180. {extremaPoints && (
  181. <div className="sparkline-extrema" aria-hidden="true">
  182. <span className="extrema-item" style={{ color: maxColor }}>
  183. ▲ {fmtExtrema(extremaPoints.max.value)}
  184. </span>
  185. <span className="extrema-item" style={{ color: minColor }}>
  186. ▼ {fmtExtrema(extremaPoints.min.value)}
  187. </span>
  188. </div>
  189. )}
  190. {legendItems.length > 0 && (
  191. <div className="sparkline-legend" aria-hidden="true">
  192. {legendItems.map((s) => (
  193. <span key={s.name} className="extrema-item" style={{ color: s.color }}>● {s.name}</span>
  194. ))}
  195. </div>
  196. )}
  197. <ResponsiveContainer width="100%" height={height} className="sparkline-svg">
  198. <AreaChart
  199. data={points}
  200. margin={{
  201. top: showAxes ? 14 : 6,
  202. right: showAxes ? 12 : 6,
  203. bottom: showAxes ? 26 : 4,
  204. left: 4,
  205. }}
  206. >
  207. <defs>
  208. <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
  209. <stop offset="0%" stopColor={stroke} stopOpacity={fillOpacity} />
  210. <stop offset="100%" stopColor={stroke} stopOpacity={0} />
  211. </linearGradient>
  212. <linearGradient id={gradId2} x1="0" y1="0" x2="0" y2="1">
  213. <stop offset="0%" stopColor={stroke2} stopOpacity={fillOpacity} />
  214. <stop offset="100%" stopColor={stroke2} stopOpacity={0} />
  215. </linearGradient>
  216. <linearGradient id={gradId3} x1="0" y1="0" x2="0" y2="1">
  217. <stop offset="0%" stopColor={stroke3} stopOpacity={fillOpacity} />
  218. <stop offset="100%" stopColor={stroke3} stopOpacity={0} />
  219. </linearGradient>
  220. </defs>
  221. {showGrid && (
  222. <CartesianGrid stroke="rgba(128, 128, 140, 0.35)" strokeDasharray="3 4" vertical={false} />
  223. )}
  224. <XAxis
  225. dataKey="label"
  226. hide={!showAxes}
  227. tick={{ fontSize: 10, fill: 'var(--ant-color-text-tertiary)' }}
  228. axisLine={false}
  229. tickLine={false}
  230. tickMargin={14}
  231. interval={0}
  232. ticks={xTickIndexes?.map((i) => points[i]?.label).filter(Boolean) as string[] | undefined}
  233. />
  234. <YAxis
  235. domain={yDomain}
  236. hide={!showAxes}
  237. tick={{ fontSize: 10, fill: 'var(--ant-color-text-tertiary)', dx: -4 }}
  238. axisLine={false}
  239. tickLine={false}
  240. tickMargin={8}
  241. tickFormatter={yFormatter}
  242. ticks={yTicks}
  243. width={56}
  244. />
  245. {showTooltip && (
  246. <Tooltip
  247. cursor={{ stroke: 'var(--ant-color-border)', strokeDasharray: '2 4' }}
  248. contentStyle={{
  249. background: 'var(--ant-color-bg-elevated)',
  250. border: '1px solid var(--ant-color-border-secondary)',
  251. borderRadius: 6,
  252. fontSize: 12,
  253. padding: '6px 10px',
  254. boxShadow: '0 4px 14px rgba(0, 0, 0, 0.12)',
  255. }}
  256. labelStyle={{ color: 'var(--ant-color-text-tertiary)', marginBottom: 4, fontSize: 11 }}
  257. itemStyle={{ color: 'var(--ant-color-text)', padding: 0, fontWeight: 500 }}
  258. formatter={(v, name) => [fmtTooltip(Number(v) || 0), multiSeries && typeof name === 'string' ? name : '']}
  259. labelFormatter={(label) => (tooltipLabelFormatter ? tooltipLabelFormatter(String(label)) : String(label))}
  260. separator={multiSeries ? ': ' : ''}
  261. />
  262. )}
  263. {referenceLines?.map((rl, idx) => (
  264. <ReferenceLine
  265. key={`ref-${idx}-${rl.y}`}
  266. y={rl.y}
  267. stroke={rl.color || stroke}
  268. strokeDasharray={rl.dash || '5 4'}
  269. strokeWidth={1.4}
  270. label={rl.label ? {
  271. value: rl.label,
  272. position: 'insideTopRight',
  273. fill: rl.color || stroke,
  274. fontSize: 10,
  275. fontWeight: 600,
  276. } : undefined}
  277. ifOverflow="extendDomain"
  278. />
  279. ))}
  280. {extremaPoints && (
  281. <>
  282. <ReferenceDot
  283. x={extremaPoints.max.label}
  284. y={extremaPoints.max.value}
  285. r={4.5}
  286. fill={maxColor}
  287. stroke="var(--ant-color-bg-elevated)"
  288. strokeWidth={2}
  289. ifOverflow="extendDomain"
  290. />
  291. <ReferenceDot
  292. x={extremaPoints.min.label}
  293. y={extremaPoints.min.value}
  294. r={4.5}
  295. fill={minColor}
  296. stroke="var(--ant-color-bg-elevated)"
  297. strokeWidth={2}
  298. ifOverflow="extendDomain"
  299. />
  300. </>
  301. )}
  302. <Area
  303. type="monotone"
  304. dataKey="value"
  305. name={multiSeries ? name1 : undefined}
  306. stroke={stroke}
  307. strokeWidth={strokeWidth}
  308. fill={`url(#${gradId})`}
  309. dot={false}
  310. activeDot={showMarker ? { r: markerRadius, fill: stroke, strokeWidth: 0 } : false}
  311. isAnimationActive={false}
  312. />
  313. {hasSeries2 && (
  314. <Area
  315. type="monotone"
  316. dataKey="value2"
  317. name={name2}
  318. stroke={stroke2}
  319. strokeWidth={strokeWidth}
  320. fill={`url(#${gradId2})`}
  321. dot={false}
  322. activeDot={showMarker ? { r: markerRadius, fill: stroke2, strokeWidth: 0 } : false}
  323. isAnimationActive={false}
  324. />
  325. )}
  326. {hasSeries3 && (
  327. <Area
  328. type="monotone"
  329. dataKey="value3"
  330. name={name3}
  331. stroke={stroke3}
  332. strokeWidth={strokeWidth}
  333. fill={`url(#${gradId3})`}
  334. dot={false}
  335. activeDot={showMarker ? { r: markerRadius, fill: stroke3, strokeWidth: 0 } : false}
  336. isAnimationActive={false}
  337. />
  338. )}
  339. </AreaChart>
  340. </ResponsiveContainer>
  341. </div>
  342. );
  343. }