-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathAprHistoryChart.tsx
More file actions
342 lines (303 loc) · 11.4 KB
/
Copy pathAprHistoryChart.tsx
File metadata and controls
342 lines (303 loc) · 11.4 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/**
* AprHistoryChart
*
* Renders a 30 / 90 / 365-day APR history sparkline for a single credit
* line. The chart is entirely SVG-based — no third-party charting library
* is required — and consumes the design-token CSS custom properties that
* every other Creditra component uses.
*
* Props
* ─────
* history – Array of { date, apr } entries, sorted oldest→newest.
* Typically sourced from `CreditLine.aprHistory`.
* lineId – Stable ID used to scope aria labels and SVG clip-path ids.
* label – Optional accessible chart title (default: "APR History").
*
* Accessibility
* ─────────────
* • Window buttons expose role="group" + aria-label on the toolbar.
* • The active window button is aria-pressed="true".
* • The SVG has role="img" and an aria-labelledby pointing to a hidden
* <title> element that summarises the visible range.
* • A <table> data summary is rendered for screen-readers (sr-only).
* • prefers-reduced-motion: area fill animation is suppressed.
*
* Theme Awareness
* ───────────────
* All colours are read from the CSS custom properties defined in
* src/index.css so dark/high-contrast overrides work automatically.
*
* @module AprHistoryChart
*/
import { useMemo, useState, useId } from "react";
import type { AprHistoryEntry } from "../types/creditLine";
import "./AprHistoryChart.css";
// ─── Types ────────────────────────────────────────────────────────────────────
export type WindowDays = 30 | 90 | 365;
export interface AprHistoryChartProps {
/** APR data points, sorted oldest→newest. */
history: AprHistoryEntry[];
/** Stable identifier for the credit line (used in aria / SVG ids). */
lineId: string;
/** Optional override for the accessible chart title. */
label?: string;
}
// ─── Constants ───────────────────────────────────────────────────────────────
const WINDOW_OPTIONS: { days: WindowDays; label: string }[] = [
{ days: 30, label: "30D" },
{ days: 90, label: "90D" },
{ days: 365, label: "365D" },
];
/** Chart drawing area dimensions (unitless — SVG viewBox coords). */
const VB_W = 300;
const VB_H = 80;
/** Horizontal padding reserved for the first/last data-point dots. */
const PADDING_X = 4;
/** Vertical padding so lines/dots are never clipped at the edge. */
const PADDING_Y = 6;
// ─── Helper: filter history to the most-recent N days ────────────────────────
function filterWindow(
history: AprHistoryEntry[],
days: WindowDays,
): AprHistoryEntry[] {
if (history.length === 0) return [];
const latestEntry = history[history.length - 1];
const cutoff = new Date(latestEntry.date);
cutoff.setDate(cutoff.getDate() - days);
const filtered = history.filter((entry) => new Date(entry.date) >= cutoff);
// Guarantee at least 2 points so the SVG path can be drawn.
// For shorter histories, show everything we have instead of hiding data.
return filtered.length >= 2
? filtered
: history.slice(-Math.min(history.length, 2));
}
// ─── Helper: project data to SVG coordinates ─────────────────────────────────
interface Point {
x: number;
y: number;
entry: AprHistoryEntry;
}
function projectPoints(entries: AprHistoryEntry[]): {
points: Point[];
minApr: number;
maxApr: number;
} {
const aprs = entries.map((e) => e.apr);
let minApr = Math.min(...aprs);
let maxApr = Math.max(...aprs);
// Ensure a minimum visible range so a flat line appears centred
if (maxApr - minApr < 0.1) {
const mid = (minApr + maxApr) / 2;
minApr = mid - 0.05;
maxApr = mid + 0.05;
}
const drawW = VB_W - PADDING_X * 2;
const drawH = VB_H - PADDING_Y * 2;
const n = entries.length;
const points: Point[] = entries.map((entry, i) => ({
x: PADDING_X + (i / (n - 1)) * drawW,
y: PADDING_Y + ((maxApr - entry.apr) / (maxApr - minApr)) * drawH,
entry,
}));
return { points, minApr, maxApr };
}
// ─── Helper: build SVG polyline points string ────────────────────────────────
function toPolylinePoints(points: Point[]): string {
return points.map((p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(" ");
}
// ─── Helper: build closed SVG path for the filled area ────────────────────────
function toAreaPath(points: Point[]): string {
if (points.length < 2) return "";
const line = points
.map((p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`)
.join(" L ");
const bottom = VB_H - PADDING_Y;
return (
`M ${points[0].x.toFixed(2)},${bottom} ` +
`L ${line} ` +
`L ${points[points.length - 1].x.toFixed(2)},${bottom} Z`
);
}
// ─── Helper: format dates for tooltips / aria ────────────────────────────────
function fmtDate(iso: string): string {
return new Date(iso).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
});
}
// ─── Component ───────────────────────────────────────────────────────────────
/**
* Sparkline chart showing APR history for a single credit line.
* Renders a window-selector toolbar (30D / 90D / 1Y) and an SVG line
* chart with a filled area and endpoint annotation dots.
*/
export function AprHistoryChart({
history,
lineId,
label = "APR History",
}: AprHistoryChartProps) {
const [window, setWindow] = useState<WindowDays>(90);
const chartTitleId = useId();
const uniqueId = useId().replace(/:/g, "");
const sanitizedLineId = lineId.replace(/[^a-z0-9]/gi, "");
const clipId = `apr-clip-${sanitizedLineId}-${uniqueId}`;
const gradientId = `apr-grad-${sanitizedLineId}-${uniqueId}`;
const visible = useMemo(
() => filterWindow(history, window),
[history, window],
);
const { points, minApr, maxApr } = useMemo(
() => projectPoints(visible),
[visible],
);
const isEmpty = points.length < 2;
const firstPoint = points[0];
const lastPoint = points[points.length - 1];
// Determine trend colour: green = falling APR (good), red = rising APR (bad)
const trendColor =
isEmpty || lastPoint.entry.apr <= firstPoint.entry.apr
? "var(--success, #3fb950)"
: "var(--error, #f85149)";
const polylinePoints = isEmpty ? "" : toPolylinePoints(points);
const areaPath = isEmpty ? "" : toAreaPath(points);
const summaryText = isEmpty
? `No ${label} data`
: `${label} from ${fmtDate(firstPoint.entry.date)} to ${fmtDate(lastPoint.entry.date)}, ` +
`range ${minApr.toFixed(2)}%–${maxApr.toFixed(2)}%`;
return (
<div className="apr-history-chart" data-testid="apr-history-chart">
{/* ── Window selector toolbar ── */}
<div
className="apr-history-chart__toolbar"
role="group"
aria-label="APR history time window"
>
<span className="apr-history-chart__title">{label}</span>
<div className="apr-history-chart__windows">
{WINDOW_OPTIONS.map(({ days, label: btnLabel }) => (
<button
key={days}
type="button"
className={`apr-history-chart__window-btn${window === days ? " active" : ""}`}
aria-pressed={window === days}
onClick={() => setWindow(days)}
>
{btnLabel}
</button>
))}
</div>
</div>
{/* ── SVG chart ── */}
<svg
className="apr-history-chart__svg"
viewBox={`0 0 ${VB_W} ${VB_H}`}
preserveAspectRatio="none"
role="img"
aria-labelledby={chartTitleId}
focusable="false"
>
{/* Accessible title (hidden visually, read by screen-readers) */}
<title id={chartTitleId}>{summaryText}</title>
<defs>
{/* Gradient fill below the line */}
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={trendColor} stopOpacity="0.22" />
<stop offset="100%" stopColor={trendColor} stopOpacity="0.02" />
</linearGradient>
{/* Clip to drawing area so dots/lines are never clipped at edges */}
<clipPath id={clipId}>
<rect x="0" y="0" width={VB_W} height={VB_H} />
</clipPath>
</defs>
{isEmpty ? (
// Empty state: render a subtle dashed centre line
<line
x1={PADDING_X}
y1={VB_H / 2}
x2={VB_W - PADDING_X}
y2={VB_H / 2}
stroke="var(--border, #30363d)"
strokeWidth="1"
strokeDasharray="4 4"
/>
) : (
<g clipPath={`url(#${clipId})`} className="apr-history-chart__series">
{/* Filled area */}
<path
className="apr-history-chart__area"
d={areaPath}
fill={`url(#${gradientId})`}
/>
{/* Line */}
<polyline
className="apr-history-chart__line"
points={polylinePoints}
fill="none"
stroke={trendColor}
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
{/* First-point dot */}
<circle
cx={firstPoint.x}
cy={firstPoint.y}
r="2.5"
fill={trendColor}
opacity="0.7"
aria-hidden="true"
/>
{/* Last-point dot (current APR) */}
<circle
cx={lastPoint.x}
cy={lastPoint.y}
r="3"
fill={trendColor}
aria-hidden="true"
/>
</g>
)}
</svg>
{/* ── Axis labels ── */}
{!isEmpty ? (
<div className="apr-history-chart__axis" aria-hidden="true">
<span className="apr-history-chart__axis-label">
{fmtDate(firstPoint.entry.date)}
</span>
<span
className="apr-history-chart__axis-value"
style={{ color: trendColor }}
>
{lastPoint.entry.apr.toFixed(2)}%
</span>
<span className="apr-history-chart__axis-label">
{fmtDate(lastPoint.entry.date)}
</span>
</div>
) : (
<p className="apr-history-chart__empty-copy" aria-live="polite">
No APR history available yet.
</p>
)}
{/* ── Screen-reader data table (visually hidden) ── */}
<table className="sr-only" aria-label={`${label} data table`}>
<caption>{summaryText}</caption>
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">APR (%)</th>
</tr>
</thead>
<tbody>
{visible.map((entry) => (
<tr key={entry.date}>
<td>{fmtDate(entry.date)}</td>
<td>{entry.apr.toFixed(2)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}