@bison-lab/ui 5.9.1 → 5.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/charts.mjs CHANGED
@@ -2,7 +2,8 @@
2
2
  import { t as cn } from "./utils-DPv8mMhD.mjs";
3
3
  import * as React from "react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
- import { Area, AreaChart as AreaChart$1, Bar, BarChart as BarChart$1, CartesianGrid, Cell, Legend, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
5
+ import { contrastRatio } from "@bison-lab/tokens";
6
+ import { Area, AreaChart as AreaChart$1, Bar, BarChart as BarChart$1, CartesianGrid, Cell, Legend, Line, LineChart as LineChart$1, Pie, PieChart, PolarAngleAxis, PolarGrid, PolarRadiusAxis, Radar, RadarChart as RadarChart$1, ReferenceLine, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
6
7
  //#region src/lib/chart-utils.ts
7
8
  /**
8
9
  * Shared utilities for chart components.
@@ -41,67 +42,328 @@ const chartSizeMap = {
41
42
  md: 300,
42
43
  lg: 400
43
44
  };
45
+ function hslToRgb(h, s, l) {
46
+ const chroma = (1 - Math.abs(2 * l - 1)) * s;
47
+ const hue = (h % 360 + 360) % 360 / 60;
48
+ const x = chroma * (1 - Math.abs(hue % 2 - 1));
49
+ const [r, g, b] = hue < 1 ? [
50
+ chroma,
51
+ x,
52
+ 0
53
+ ] : hue < 2 ? [
54
+ x,
55
+ chroma,
56
+ 0
57
+ ] : hue < 3 ? [
58
+ 0,
59
+ chroma,
60
+ x
61
+ ] : hue < 4 ? [
62
+ 0,
63
+ x,
64
+ chroma
65
+ ] : hue < 5 ? [
66
+ x,
67
+ 0,
68
+ chroma
69
+ ] : [
70
+ chroma,
71
+ 0,
72
+ x
73
+ ];
74
+ const m = l - chroma / 2;
75
+ return [
76
+ r,
77
+ g,
78
+ b
79
+ ].map((c) => Math.round((c + m) * 255));
80
+ }
81
+ /**
82
+ * Reads `#rgb`, `#rrggbb`, `rgb(…)`, `hsl(…)` or a bare `h s% l%` triplet
83
+ * (the form theme tokens hold). Returns null for anything else, such as a
84
+ * `var()` that has not resolved yet.
85
+ */
86
+ function parseCssColor(input) {
87
+ const value = input.trim();
88
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(value);
89
+ if (hex) {
90
+ const digits = hex[1].length === 3 ? hex[1].split("").map((d) => d + d).join("") : hex[1];
91
+ const n = parseInt(digits, 16);
92
+ return [
93
+ n >> 16 & 255,
94
+ n >> 8 & 255,
95
+ n & 255
96
+ ];
97
+ }
98
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(value);
99
+ if (rgb) return [
100
+ Number(rgb[1]),
101
+ Number(rgb[2]),
102
+ Number(rgb[3])
103
+ ];
104
+ const hsl = /^(?:hsla?\()?\s*(-?[\d.]+)(?:deg)?[\s,]+([\d.]+)%[\s,]+([\d.]+)%/i.exec(value);
105
+ if (hsl) return hslToRgb(Number(hsl[1]), Number(hsl[2]) / 100, Number(hsl[3]) / 100);
106
+ return null;
107
+ }
108
+ /** `amount` of `color` over `base`, as an opaque color. */
109
+ function mixRgb(color, base, amount) {
110
+ return color.map((c, i) => Math.round(c * amount + base[i] * (1 - amount)));
111
+ }
112
+ function rgbToHex([r, g, b]) {
113
+ return `#${[
114
+ r,
115
+ g,
116
+ b
117
+ ].map((c) => c.toString(16).padStart(2, "0")).join("")}`;
118
+ }
44
119
  //#endregion
45
- //#region src/components/area-chart.tsx
46
- const AreaChart = React.forwardRef(({ className, data, index, categories, series, colors, size = "md", height, showGrid = true, showLegend = false, showTooltip = true, showYAxis = true, curveType = "monotone", stacked = false, ...props }, ref) => {
120
+ //#region src/components/chart-parts.tsx
121
+ /**
122
+ * Axis tick text. The fill is an attribute, not a class, because recharts
123
+ * writes its own `fill="#666"` on each tick and that default misses AA in
124
+ * dark mode.
125
+ */
126
+ const chartAxisTick = {
127
+ fontSize: 12,
128
+ fill: "hsl(var(--muted-foreground))"
129
+ };
130
+ const chartAxisProps = {
131
+ tick: chartAxisTick,
132
+ tickLine: false,
133
+ axisLine: false
134
+ };
135
+ /**
136
+ * The hover highlight behind a bar category. Recharts' default is a `#ccc`
137
+ * block, which reads as a bright slab in dark mode.
138
+ */
139
+ const chartBarCursor = {
140
+ fill: "hsl(var(--muted))",
141
+ fillOpacity: .6
142
+ };
143
+ /** The hover guide line on line, area and radar charts. */
144
+ const chartLineCursor = {
145
+ stroke: "hsl(var(--border))",
146
+ strokeWidth: 1
147
+ };
148
+ /**
149
+ * Puts recharts' items back in the order the series were passed. Recharts
150
+ * sorts the legend by label and the tooltip by name by default.
151
+ */
152
+ function orderBySeries(items, order) {
153
+ if (!order || order.length === 0) return [...items];
154
+ const rank = (item) => {
155
+ const i = order.indexOf(String(item.dataKey));
156
+ return i === -1 ? order.length : i;
157
+ };
158
+ return [...items].sort((a, b) => rank(a) - rank(b));
159
+ }
160
+ /**
161
+ * The legend every chart uses: labels in the foreground color with the
162
+ * series color as a swatch. The swatch is hidden from assistive tech;
163
+ * recharts' own icons are named "<label> legend icon", which reads as
164
+ * "[object Object] legend icon" once a label is an element.
165
+ */
166
+ function ChartLegendContent({ payload, order }) {
167
+ if (!payload || payload.length === 0) return null;
168
+ return /* @__PURE__ */ jsx("ul", {
169
+ className: "flex flex-wrap items-center justify-center gap-x-4 gap-y-1 pt-3 text-xs text-foreground",
170
+ children: orderBySeries(payload, order).map((item, i) => /* @__PURE__ */ jsxs("li", {
171
+ className: "flex items-center gap-1.5",
172
+ children: [/* @__PURE__ */ jsx("span", {
173
+ "aria-hidden": "true",
174
+ "data-chart-swatch": "",
175
+ className: "size-2.5 shrink-0 rounded-sm",
176
+ style: { backgroundColor: item.color ?? "currentColor" }
177
+ }), /* @__PURE__ */ jsx("span", { children: item.value })]
178
+ }, `${String(item.dataKey ?? item.value)}-${i}`))
179
+ });
180
+ }
181
+ function itemColor(item) {
182
+ const fromPayload = item.payload && typeof item.payload === "object" && "fill" in item.payload ? item.payload.fill : void 0;
183
+ return item.color ?? item.fill ?? (typeof fromPayload === "string" ? fromPayload : void 0) ?? item.stroke ?? "currentColor";
184
+ }
185
+ /**
186
+ * The tooltip body every chart uses. Rows are in the foreground color with
187
+ * the series color as a swatch: the series color as small text is too faint.
188
+ */
189
+ function ChartTooltipContent({ active, payload, label, valueFormatter, order }) {
190
+ if (!active || !payload || payload.length === 0) return null;
191
+ return /* @__PURE__ */ jsxs("div", {
192
+ role: "status",
193
+ "aria-live": "polite",
194
+ className: "min-w-32 rounded-md border border-border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-md",
195
+ children: [label != null && label !== "" && /* @__PURE__ */ jsx("p", {
196
+ className: "mb-1 font-medium",
197
+ children: label
198
+ }), /* @__PURE__ */ jsx("ul", {
199
+ className: "flex flex-col gap-1",
200
+ children: orderBySeries(payload, order).map((item, i) => {
201
+ const value = typeof item.value === "number" && valueFormatter ? valueFormatter(item.value) : item.value == null ? "–" : String(item.value);
202
+ return /* @__PURE__ */ jsxs("li", {
203
+ className: "flex items-center gap-2",
204
+ children: [
205
+ /* @__PURE__ */ jsx("span", {
206
+ "aria-hidden": "true",
207
+ "data-chart-swatch": "",
208
+ className: "size-2.5 shrink-0 rounded-sm",
209
+ style: { backgroundColor: itemColor(item) }
210
+ }),
211
+ /* @__PURE__ */ jsx("span", { children: item.name }),
212
+ /* @__PURE__ */ jsx("span", {
213
+ className: "ml-auto pl-3 font-medium tabular-nums",
214
+ children: value
215
+ })
216
+ ]
217
+ }, `${String(item.dataKey ?? item.name)}-${i}`);
218
+ })
219
+ })]
220
+ });
221
+ }
222
+ /** The accessible name a chart region gets when no `summary` is passed. */
223
+ function chartLabel(summary, props, fallback) {
224
+ return summary ?? props["aria-label"] ?? props.title ?? fallback;
225
+ }
226
+ /**
227
+ * The chart's data as a visually hidden table, so a screen reader can read
228
+ * every value without the hover tooltip.
229
+ */
230
+ function ChartDataTable({ caption, indexHeader, rows, columns }) {
231
+ return /* @__PURE__ */ jsx("div", {
232
+ className: "sr-only",
233
+ children: /* @__PURE__ */ jsxs("table", {
234
+ "data-chart-table": "",
235
+ children: [
236
+ /* @__PURE__ */ jsx("caption", { children: caption }),
237
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
238
+ scope: "col",
239
+ children: indexHeader
240
+ }), columns.map((c, i) => /* @__PURE__ */ jsx("th", {
241
+ scope: "col",
242
+ children: c
243
+ }, i))] }) }),
244
+ /* @__PURE__ */ jsx("tbody", { children: rows.map((row, r) => /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
245
+ scope: "row",
246
+ children: row.label
247
+ }), row.values.map((v, c) => /* @__PURE__ */ jsx("td", { children: v }, c))] }, r)) })
248
+ ]
249
+ })
250
+ });
251
+ }
252
+ /** Formats a raw cell for the hidden data table. */
253
+ function formatChartValue(value, valueFormatter) {
254
+ if (typeof value === "number") return valueFormatter ? valueFormatter(value) : String(value);
255
+ if (value == null || value === "") return "No data";
256
+ return String(value);
257
+ }
258
+ /**
259
+ * A counter that ticks when the root element's class, style or `data-theme`
260
+ * changes, so colors read from theme tokens are read again after a light or
261
+ * dark switch instead of keeping the values from mount.
262
+ */
263
+ function useThemeVersion() {
264
+ const [version, setVersion] = React.useState(0);
265
+ React.useEffect(() => {
266
+ if (typeof MutationObserver === "undefined") return;
267
+ const observer = new MutationObserver(() => setVersion((v) => v + 1));
268
+ observer.observe(document.documentElement, {
269
+ attributes: true,
270
+ attributeFilter: [
271
+ "class",
272
+ "style",
273
+ "data-theme"
274
+ ]
275
+ });
276
+ return () => observer.disconnect();
277
+ }, []);
278
+ return version;
279
+ }
280
+ /**
281
+ * The resolved series colors (theme tokens unless `colors` is passed) and a
282
+ * ref callback that also forwards the consumer's ref.
283
+ */
284
+ function useChartColors(colors, forwardedRef) {
47
285
  const containerRef = React.useRef(null);
48
286
  const [themeColors, setThemeColors] = React.useState([]);
287
+ const themeVersion = useThemeVersion();
49
288
  React.useEffect(() => {
50
- const el = containerRef.current;
51
- setThemeColors(colors ?? getThemeColors(el));
52
- }, [colors]);
53
- const resolvedSeries = React.useMemo(() => {
54
- if (series) return series;
55
- return (categories ?? []).map((key) => ({
56
- dataKey: key,
57
- name: key
58
- }));
59
- }, [series, categories]);
60
- const chartHeight = height ?? chartSizeMap[size];
61
- const gridColor = themeColors.length > 0 ? void 0 : "hsl(var(--border-subtle))";
62
- return /* @__PURE__ */ jsx("div", {
63
- ref: (node) => {
289
+ setThemeColors(colors ?? getThemeColors(containerRef.current));
290
+ }, [colors, themeVersion]);
291
+ return {
292
+ setRef: React.useCallback((node) => {
64
293
  containerRef.current = node;
65
- if (typeof ref === "function") ref(node);
66
- else if (ref) ref.current = node;
67
- },
68
- className: cn("w-full", className),
294
+ if (typeof forwardedRef === "function") forwardedRef(node);
295
+ else if (forwardedRef) forwardedRef.current = node;
296
+ }, [forwardedRef]),
297
+ themeColors,
298
+ colorAt: React.useCallback((i, override) => override ?? themeColors[i % themeColors.length] ?? "hsl(var(--primary))", [themeColors]),
299
+ containerRef,
300
+ themeVersion
301
+ };
302
+ }
303
+ /** The chart region: a named figure around the drawing and its data table. */
304
+ const ChartFrame = React.forwardRef(({ label, className, children, ...props }, ref) => /* @__PURE__ */ jsx("div", {
305
+ ref,
306
+ role: "figure",
307
+ className: cn("w-full", className),
308
+ ...props,
309
+ "aria-label": label,
310
+ children
311
+ }));
312
+ ChartFrame.displayName = "ChartFrame";
313
+ /** A series config every cartesian chart accepts in its quick form. */
314
+ function seriesFromCategories(series, categories) {
315
+ if (series) return series;
316
+ return (categories ?? []).map((key) => ({
317
+ dataKey: key,
318
+ name: key
319
+ }));
320
+ }
321
+ //#endregion
322
+ //#region src/components/area-chart.tsx
323
+ const AreaChart = React.forwardRef(({ className, data, index, categories, series, colors, size = "md", height, showGrid = true, showLegend = false, showTooltip = true, showYAxis = true, curveType = "monotone", stacked = false, summary, valueFormatter, ...props }, ref) => {
324
+ const { setRef, colorAt } = useChartColors(colors, ref);
325
+ const resolvedSeries = React.useMemo(() => seriesFromCategories(series, categories), [series, categories]);
326
+ const order = React.useMemo(() => resolvedSeries.map((s) => s.dataKey), [resolvedSeries]);
327
+ const chartHeight = height ?? chartSizeMap[size];
328
+ const label = chartLabel(summary, props, "Area chart");
329
+ return /* @__PURE__ */ jsxs(ChartFrame, {
330
+ ref: setRef,
331
+ label,
332
+ className,
69
333
  ...props,
70
- children: /* @__PURE__ */ jsx(ResponsiveContainer, {
334
+ children: [/* @__PURE__ */ jsx(ResponsiveContainer, {
71
335
  width: "100%",
72
336
  height: chartHeight,
73
337
  children: /* @__PURE__ */ jsxs(AreaChart$1, {
74
338
  data,
339
+ accessibilityLayer: true,
340
+ title: label,
75
341
  children: [
76
342
  showGrid && /* @__PURE__ */ jsx(CartesianGrid, {
77
343
  strokeDasharray: "3 3",
78
- stroke: gridColor,
79
- className: "stroke-border-subtle"
344
+ stroke: "hsl(var(--border-subtle))"
80
345
  }),
81
346
  /* @__PURE__ */ jsx(XAxis, {
82
347
  dataKey: index,
83
- tick: { fontSize: 12 },
84
- tickLine: false,
85
- axisLine: false,
86
- className: "[&_text]:fill-content-secondary"
348
+ ...chartAxisProps
87
349
  }),
88
350
  showYAxis && /* @__PURE__ */ jsx(YAxis, {
89
- tick: { fontSize: 12 },
90
- tickLine: false,
91
- axisLine: false,
92
- width: 40,
93
- className: "[&_text]:fill-content-secondary"
351
+ ...chartAxisProps,
352
+ width: 40
353
+ }),
354
+ showTooltip && /* @__PURE__ */ jsx(Tooltip, {
355
+ cursor: chartLineCursor,
356
+ content: /* @__PURE__ */ jsx(ChartTooltipContent, {
357
+ valueFormatter,
358
+ order
359
+ })
360
+ }),
361
+ showLegend && /* @__PURE__ */ jsx(Legend, {
362
+ itemSorter: null,
363
+ content: /* @__PURE__ */ jsx(ChartLegendContent, { order })
94
364
  }),
95
- showTooltip && /* @__PURE__ */ jsx(Tooltip, { contentStyle: {
96
- backgroundColor: "hsl(var(--popover))",
97
- border: "1px solid hsl(var(--border))",
98
- borderRadius: "var(--radius-md)",
99
- color: "hsl(var(--popover-foreground))",
100
- fontSize: 12
101
- } }),
102
- showLegend && /* @__PURE__ */ jsx(Legend, {}),
103
365
  resolvedSeries.map((s, i) => {
104
- const color = s.color ?? themeColors[i % themeColors.length] ?? `hsl(var(--primary))`;
366
+ const color = colorAt(i, s.color);
105
367
  return /* @__PURE__ */ jsx(Area, {
106
368
  type: curveType,
107
369
  dataKey: s.dataKey,
@@ -114,161 +376,501 @@ const AreaChart = React.forwardRef(({ className, data, index, categories, series
114
376
  })
115
377
  ]
116
378
  })
117
- })
379
+ }), /* @__PURE__ */ jsx(ChartDataTable, {
380
+ caption: label,
381
+ indexHeader: index,
382
+ columns: resolvedSeries.map((s) => s.name ?? s.dataKey),
383
+ rows: data.map((row) => ({
384
+ label: String(row[index] ?? ""),
385
+ values: resolvedSeries.map((s) => formatChartValue(row[s.dataKey], valueFormatter))
386
+ }))
387
+ })]
118
388
  });
119
389
  });
120
390
  AreaChart.displayName = "AreaChart";
121
391
  //#endregion
122
392
  //#region src/components/bar-chart.tsx
123
- const BarChart = React.forwardRef(({ className, data, index, categories, series, colors, size = "md", height, showGrid = true, showLegend = false, showTooltip = true, showYAxis = true, stacked = false, horizontal = false, maxValue, ...props }, ref) => {
124
- const containerRef = React.useRef(null);
125
- const [themeColors, setThemeColors] = React.useState([]);
126
- React.useEffect(() => {
127
- const el = containerRef.current;
128
- setThemeColors(colors ?? getThemeColors(el));
129
- }, [colors]);
130
- const resolvedSeries = React.useMemo(() => {
131
- if (series) return series;
132
- return (categories ?? []).map((key) => ({
133
- dataKey: key,
134
- name: key
135
- }));
136
- }, [series, categories]);
393
+ const formatPercent$1 = (value) => `${Math.round(value * 10) / 10}%`;
394
+ const numberAt = (row, key) => {
395
+ const v = row[key];
396
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
397
+ };
398
+ const BarChart = React.forwardRef(({ className, data, index, categories, series, colors, size = "md", height, showGrid = true, showLegend = false, showTooltip = true, showYAxis = true, stacked = false, stackMode, horizontal = false, categoryAxisWidth = 80, maxValue, summary, valueFormatter, ...props }, ref) => {
399
+ const { setRef, colorAt } = useChartColors(colors, ref);
400
+ const resolvedSeries = React.useMemo(() => seriesFromCategories(series, categories), [series, categories]);
401
+ const mode = stackMode ?? (stacked ? "normal" : void 0);
402
+ const isStacked = mode !== void 0;
403
+ const isPercent = mode === "percent";
404
+ const format = valueFormatter ?? (isPercent ? formatPercent$1 : void 0);
405
+ const chartData = React.useMemo(() => {
406
+ if (!isPercent) return data;
407
+ return data.map((row) => {
408
+ const total = resolvedSeries.reduce((sum, s) => sum + Math.max(0, numberAt(row, s.dataKey)), 0);
409
+ const next = { ...row };
410
+ for (const s of resolvedSeries) next[s.dataKey] = total > 0 ? Math.max(0, numberAt(row, s.dataKey)) / total * 100 : 0;
411
+ return next;
412
+ });
413
+ }, [
414
+ data,
415
+ isPercent,
416
+ resolvedSeries
417
+ ]);
418
+ const outerSeriesByRow = React.useMemo(() => {
419
+ if (!isStacked) return null;
420
+ return chartData.map((row) => {
421
+ for (let i = resolvedSeries.length - 1; i >= 0; i--) if (numberAt(row, resolvedSeries[i].dataKey) > 0) return i;
422
+ return -1;
423
+ });
424
+ }, [
425
+ chartData,
426
+ isStacked,
427
+ resolvedSeries
428
+ ]);
429
+ const order = React.useMemo(() => resolvedSeries.map((s) => s.dataKey), [resolvedSeries]);
137
430
  const chartHeight = height ?? chartSizeMap[size];
138
431
  const layout = horizontal ? "vertical" : "horizontal";
139
- return /* @__PURE__ */ jsx("div", {
140
- ref: (node) => {
141
- containerRef.current = node;
142
- if (typeof ref === "function") ref(node);
143
- else if (ref) ref.current = node;
144
- },
145
- className: cn("w-full", className),
432
+ const outerRadius = horizontal ? [
433
+ 0,
434
+ 4,
435
+ 4,
436
+ 0
437
+ ] : [
438
+ 4,
439
+ 4,
440
+ 0,
441
+ 0
442
+ ];
443
+ const flat = [
444
+ 0,
445
+ 0,
446
+ 0,
447
+ 0
448
+ ];
449
+ const label = chartLabel(summary, props, "Bar chart");
450
+ const numericDomain = isPercent ? {
451
+ domain: [0, 100],
452
+ allowDataOverflow: true,
453
+ ticks: [
454
+ 0,
455
+ 25,
456
+ 50,
457
+ 75,
458
+ 100
459
+ ],
460
+ tickFormatter: (v) => `${v}%`
461
+ } : maxValue != null ? { domain: [0, maxValue] } : {};
462
+ return /* @__PURE__ */ jsxs(ChartFrame, {
463
+ ref: setRef,
464
+ label,
465
+ className,
146
466
  ...props,
147
- children: /* @__PURE__ */ jsx(ResponsiveContainer, {
467
+ children: [/* @__PURE__ */ jsx(ResponsiveContainer, {
148
468
  width: "100%",
149
469
  height: chartHeight,
150
470
  children: /* @__PURE__ */ jsxs(BarChart$1, {
151
- data,
471
+ data: chartData,
152
472
  layout,
473
+ accessibilityLayer: true,
474
+ title: label,
153
475
  children: [
154
476
  showGrid && /* @__PURE__ */ jsx(CartesianGrid, {
155
477
  strokeDasharray: "3 3",
156
- className: "stroke-border-subtle"
478
+ stroke: "hsl(var(--border-subtle))"
157
479
  }),
158
480
  horizontal ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(XAxis, {
159
481
  type: "number",
160
- tick: { fontSize: 12 },
161
- tickLine: false,
162
- axisLine: false,
163
- className: "[&_text]:fill-content-secondary",
164
- ...maxValue != null && { domain: [0, maxValue] }
482
+ ...chartAxisProps,
483
+ ...numericDomain
165
484
  }), /* @__PURE__ */ jsx(YAxis, {
166
485
  dataKey: index,
167
486
  type: "category",
168
- tick: { fontSize: 12 },
169
- tickLine: false,
170
- axisLine: false,
171
- width: 80,
172
- className: "[&_text]:fill-content-secondary"
487
+ ...chartAxisProps,
488
+ width: categoryAxisWidth
173
489
  })] }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(XAxis, {
174
490
  dataKey: index,
175
- tick: { fontSize: 12 },
176
- tickLine: false,
177
- axisLine: false,
178
- className: "[&_text]:fill-content-secondary"
491
+ ...chartAxisProps
179
492
  }), showYAxis && /* @__PURE__ */ jsx(YAxis, {
180
- tick: { fontSize: 12 },
181
- tickLine: false,
182
- axisLine: false,
183
- ...maxValue != null && { domain: [0, maxValue] },
184
- width: 40,
185
- className: "[&_text]:fill-content-secondary"
493
+ ...chartAxisProps,
494
+ ...numericDomain,
495
+ width: isPercent ? 48 : 40
186
496
  })] }),
187
- showTooltip && /* @__PURE__ */ jsx(Tooltip, { contentStyle: {
188
- backgroundColor: "hsl(var(--popover))",
189
- border: "1px solid hsl(var(--border))",
190
- borderRadius: "var(--radius-md)",
191
- color: "hsl(var(--popover-foreground))",
192
- fontSize: 12
193
- } }),
194
- showLegend && /* @__PURE__ */ jsx(Legend, {}),
497
+ showTooltip && /* @__PURE__ */ jsx(Tooltip, {
498
+ cursor: chartBarCursor,
499
+ content: /* @__PURE__ */ jsx(ChartTooltipContent, {
500
+ valueFormatter: format,
501
+ order
502
+ })
503
+ }),
504
+ showLegend && /* @__PURE__ */ jsx(Legend, {
505
+ itemSorter: null,
506
+ content: /* @__PURE__ */ jsx(ChartLegendContent, { order })
507
+ }),
195
508
  resolvedSeries.map((s, i) => {
196
- const color = s.color ?? themeColors[i % themeColors.length] ?? `hsl(var(--primary))`;
509
+ const color = colorAt(i, s.color);
510
+ const rounded = s.radius ?? outerRadius;
197
511
  return /* @__PURE__ */ jsx(Bar, {
198
512
  dataKey: s.dataKey,
199
513
  name: s.name ?? s.dataKey,
200
514
  fill: color,
201
- radius: s.radius ?? [
202
- 4,
203
- 4,
204
- 0,
205
- 0
206
- ],
207
- stackId: stacked ? "stack" : void 0
515
+ radius: outerSeriesByRow ? flat : rounded,
516
+ stackId: isStacked ? "stack" : void 0,
517
+ children: outerSeriesByRow?.map((outer, row) => /* @__PURE__ */ jsx(Cell, {
518
+ fill: color,
519
+ radius: outer === i ? rounded : flat
520
+ }, row))
208
521
  }, s.dataKey);
209
522
  })
210
523
  ]
211
524
  })
212
- })
525
+ }), /* @__PURE__ */ jsx(ChartDataTable, {
526
+ caption: label,
527
+ indexHeader: index,
528
+ columns: resolvedSeries.map((s) => s.name ?? s.dataKey),
529
+ rows: chartData.map((row) => ({
530
+ label: String(row[index] ?? ""),
531
+ values: resolvedSeries.map((s) => formatChartValue(row[s.dataKey], format))
532
+ }))
533
+ })]
213
534
  });
214
535
  });
215
536
  BarChart.displayName = "BarChart";
216
537
  //#endregion
217
538
  //#region src/components/donut-chart.tsx
218
- const DonutChart = React.forwardRef(({ className, data, nameKey = "name", dataKey = "value", colors, size = "md", height, showLegend = false, showTooltip = true, showLabels = false, innerRadius = "60%", outerRadius = "80%", paddingAngle = 2, centerLabel, ...props }, ref) => {
219
- const containerRef = React.useRef(null);
220
- const [themeColors, setThemeColors] = React.useState([]);
221
- React.useEffect(() => {
222
- const el = containerRef.current;
223
- setThemeColors(colors ?? getThemeColors(el));
224
- }, [colors]);
539
+ const DonutChart = React.forwardRef(({ className, data, nameKey = "name", dataKey = "value", colors, size = "md", height, showLegend = false, showTooltip = true, showLabels = false, innerRadius = "60%", outerRadius = "80%", paddingAngle = 2, centerLabel, summary, valueFormatter, ...props }, ref) => {
540
+ const { setRef, colorAt } = useChartColors(colors, ref);
225
541
  const chartHeight = height ?? chartSizeMap[size];
226
- return /* @__PURE__ */ jsxs("div", {
227
- ref: (node) => {
228
- containerRef.current = node;
229
- if (typeof ref === "function") ref(node);
230
- else if (ref) ref.current = node;
231
- },
232
- className: cn("relative w-full", className),
542
+ const label = chartLabel(summary, props, "Donut chart");
543
+ return /* @__PURE__ */ jsxs(ChartFrame, {
544
+ ref: setRef,
545
+ label,
546
+ className: cn("relative", className),
233
547
  ...props,
234
- children: [centerLabel && /* @__PURE__ */ jsx("div", {
235
- className: "pointer-events-none absolute inset-0 flex items-center justify-center",
236
- "aria-hidden": "true",
237
- children: /* @__PURE__ */ jsx("div", {
238
- className: "text-center",
239
- children: centerLabel
548
+ children: [
549
+ centerLabel && /* @__PURE__ */ jsx("div", {
550
+ className: "pointer-events-none absolute inset-0 flex items-center justify-center",
551
+ "aria-hidden": "true",
552
+ children: /* @__PURE__ */ jsx("div", {
553
+ className: "text-center",
554
+ children: centerLabel
555
+ })
556
+ }),
557
+ /* @__PURE__ */ jsx(ResponsiveContainer, {
558
+ width: "100%",
559
+ height: chartHeight,
560
+ children: /* @__PURE__ */ jsxs(PieChart, {
561
+ accessibilityLayer: true,
562
+ title: label,
563
+ children: [
564
+ /* @__PURE__ */ jsx(Pie, {
565
+ data,
566
+ nameKey,
567
+ dataKey,
568
+ innerRadius,
569
+ outerRadius,
570
+ paddingAngle,
571
+ label: showLabels,
572
+ strokeWidth: 0,
573
+ children: data.map((_, i) => /* @__PURE__ */ jsx(Cell, { fill: colorAt(i) }, i))
574
+ }),
575
+ showTooltip && /* @__PURE__ */ jsx(Tooltip, { content: /* @__PURE__ */ jsx(ChartTooltipContent, { valueFormatter }) }),
576
+ showLegend && /* @__PURE__ */ jsx(Legend, {
577
+ itemSorter: null,
578
+ content: /* @__PURE__ */ jsx(ChartLegendContent, {})
579
+ })
580
+ ]
581
+ })
582
+ }),
583
+ /* @__PURE__ */ jsx(ChartDataTable, {
584
+ caption: label,
585
+ indexHeader: nameKey,
586
+ columns: [dataKey],
587
+ rows: data.map((row) => ({
588
+ label: String(row[nameKey] ?? ""),
589
+ values: [formatChartValue(row[dataKey], valueFormatter)]
590
+ }))
240
591
  })
241
- }), /* @__PURE__ */ jsx(ResponsiveContainer, {
592
+ ]
593
+ });
594
+ });
595
+ DonutChart.displayName = "DonutChart";
596
+ //#endregion
597
+ //#region src/components/line-chart.tsx
598
+ const isValue = (v) => typeof v === "number" && Number.isFinite(v);
599
+ /** True when no two neighboring rows both have a value, so no segment can be drawn. */
600
+ function cannotDrawLine(data, key) {
601
+ for (let i = 1; i < data.length; i++) if (isValue(data[i - 1][key]) && isValue(data[i][key])) return false;
602
+ return true;
603
+ }
604
+ const LineChart = React.forwardRef(({ className, data, index, categories, series, colors, size = "md", height, showGrid = true, showLegend = false, showTooltip = true, showYAxis = true, showDots = false, curveType = "monotone", referenceLine, yDomain, summary, valueFormatter, ...props }, ref) => {
605
+ const { setRef, colorAt } = useChartColors(colors, ref);
606
+ const resolvedSeries = React.useMemo(() => seriesFromCategories(series, categories), [series, categories]);
607
+ const order = React.useMemo(() => resolvedSeries.map((s) => s.dataKey), [resolvedSeries]);
608
+ const chartHeight = height ?? chartSizeMap[size];
609
+ const label = chartLabel(summary, props, "Line chart");
610
+ return /* @__PURE__ */ jsxs(ChartFrame, {
611
+ ref: setRef,
612
+ label,
613
+ className,
614
+ ...props,
615
+ children: [/* @__PURE__ */ jsx(ResponsiveContainer, {
242
616
  width: "100%",
243
617
  height: chartHeight,
244
- children: /* @__PURE__ */ jsxs(PieChart, { children: [
245
- /* @__PURE__ */ jsx(Pie, {
246
- data,
247
- nameKey,
248
- dataKey,
249
- innerRadius,
250
- outerRadius,
251
- paddingAngle,
252
- label: showLabels,
253
- strokeWidth: 0,
254
- children: data.map((_, i) => {
255
- return /* @__PURE__ */ jsx(Cell, { fill: themeColors[i % themeColors.length] ?? `hsl(var(--primary))` }, i);
618
+ children: /* @__PURE__ */ jsxs(LineChart$1, {
619
+ data,
620
+ accessibilityLayer: true,
621
+ title: label,
622
+ children: [
623
+ showGrid && /* @__PURE__ */ jsx(CartesianGrid, {
624
+ strokeDasharray: "3 3",
625
+ stroke: "hsl(var(--border-subtle))"
626
+ }),
627
+ /* @__PURE__ */ jsx(XAxis, {
628
+ dataKey: index,
629
+ ...chartAxisProps
630
+ }),
631
+ showYAxis && /* @__PURE__ */ jsx(YAxis, {
632
+ ...chartAxisProps,
633
+ width: 40,
634
+ ...yDomain && { domain: yDomain }
635
+ }),
636
+ showTooltip && /* @__PURE__ */ jsx(Tooltip, {
637
+ cursor: chartLineCursor,
638
+ content: /* @__PURE__ */ jsx(ChartTooltipContent, {
639
+ valueFormatter,
640
+ order
641
+ })
642
+ }),
643
+ showLegend && /* @__PURE__ */ jsx(Legend, {
644
+ itemSorter: null,
645
+ content: /* @__PURE__ */ jsx(ChartLegendContent, { order })
646
+ }),
647
+ referenceLine && /* @__PURE__ */ jsx(ReferenceLine, {
648
+ y: referenceLine.value,
649
+ stroke: referenceLine.color ?? "hsl(var(--muted-foreground))",
650
+ strokeDasharray: "4 4",
651
+ ifOverflow: "extendDomain",
652
+ label: referenceLine.label ? {
653
+ value: referenceLine.label,
654
+ position: "insideTopRight",
655
+ ...chartAxisTick
656
+ } : void 0
657
+ }),
658
+ resolvedSeries.map((s, i) => {
659
+ const color = colorAt(i, s.color);
660
+ const dots = (s.showDots ?? showDots) || cannotDrawLine(data, s.dataKey);
661
+ return /* @__PURE__ */ jsx(Line, {
662
+ type: curveType,
663
+ dataKey: s.dataKey,
664
+ name: s.name ?? s.dataKey,
665
+ stroke: color,
666
+ strokeWidth: 2,
667
+ strokeDasharray: s.dashed ? "6 4" : void 0,
668
+ dot: dots ? {
669
+ r: 3,
670
+ fill: color,
671
+ stroke: color,
672
+ strokeWidth: 1,
673
+ strokeDasharray: "none"
674
+ } : false,
675
+ activeDot: {
676
+ r: 4,
677
+ fill: color,
678
+ stroke: "hsl(var(--background))",
679
+ strokeWidth: 2
680
+ }
681
+ }, s.dataKey);
256
682
  })
257
- }),
258
- showTooltip && /* @__PURE__ */ jsx(Tooltip, { contentStyle: {
259
- backgroundColor: "hsl(var(--popover))",
260
- border: "1px solid hsl(var(--border))",
261
- borderRadius: "var(--radius-md)",
262
- color: "hsl(var(--popover-foreground))",
263
- fontSize: 12
264
- } }),
265
- showLegend && /* @__PURE__ */ jsx(Legend, {})
266
- ] })
683
+ ]
684
+ })
685
+ }), /* @__PURE__ */ jsx(ChartDataTable, {
686
+ caption: label,
687
+ indexHeader: index,
688
+ columns: resolvedSeries.map((s) => s.name ?? s.dataKey),
689
+ rows: data.map((row) => ({
690
+ label: String(row[index] ?? ""),
691
+ values: resolvedSeries.map((s) => formatChartValue(row[s.dataKey], valueFormatter))
692
+ }))
267
693
  })]
268
694
  });
269
695
  });
270
- DonutChart.displayName = "DonutChart";
696
+ LineChart.displayName = "LineChart";
697
+ //#endregion
698
+ //#region src/components/radar-chart.tsx
699
+ const RadarChart = React.forwardRef(({ className, data, index, categories, series, colors, size = "md", height, showGrid = true, showLegend = false, showTooltip = true, maxValue, summary, valueFormatter, ...props }, ref) => {
700
+ const { setRef, colorAt } = useChartColors(colors, ref);
701
+ const resolvedSeries = React.useMemo(() => seriesFromCategories(series, categories), [series, categories]);
702
+ const order = React.useMemo(() => resolvedSeries.map((s) => s.dataKey), [resolvedSeries]);
703
+ const chartHeight = height ?? chartSizeMap[size];
704
+ const label = chartLabel(summary, props, "Radar chart");
705
+ return /* @__PURE__ */ jsxs(ChartFrame, {
706
+ ref: setRef,
707
+ label,
708
+ className,
709
+ ...props,
710
+ children: [/* @__PURE__ */ jsx(ResponsiveContainer, {
711
+ width: "100%",
712
+ height: chartHeight,
713
+ children: /* @__PURE__ */ jsxs(RadarChart$1, {
714
+ data,
715
+ outerRadius: "72%",
716
+ accessibilityLayer: true,
717
+ title: label,
718
+ children: [
719
+ showGrid && /* @__PURE__ */ jsx(PolarGrid, { stroke: "hsl(var(--border))" }),
720
+ /* @__PURE__ */ jsx(PolarAngleAxis, {
721
+ dataKey: index,
722
+ tick: chartAxisTick
723
+ }),
724
+ /* @__PURE__ */ jsx(PolarRadiusAxis, {
725
+ domain: [0, maxValue ?? "auto"],
726
+ tick: false,
727
+ axisLine: false
728
+ }),
729
+ showTooltip && /* @__PURE__ */ jsx(Tooltip, {
730
+ cursor: chartLineCursor,
731
+ content: /* @__PURE__ */ jsx(ChartTooltipContent, {
732
+ valueFormatter,
733
+ order
734
+ })
735
+ }),
736
+ showLegend && /* @__PURE__ */ jsx(Legend, {
737
+ itemSorter: null,
738
+ content: /* @__PURE__ */ jsx(ChartLegendContent, { order })
739
+ }),
740
+ resolvedSeries.map((s, i) => {
741
+ const color = colorAt(i, s.color);
742
+ return /* @__PURE__ */ jsx(Radar, {
743
+ dataKey: s.dataKey,
744
+ name: s.name ?? s.dataKey,
745
+ stroke: color,
746
+ strokeWidth: 2,
747
+ strokeDasharray: s.dashed ? "6 4" : void 0,
748
+ fill: color,
749
+ fillOpacity: s.fillOpacity ?? (s.dashed ? 0 : .2)
750
+ }, s.dataKey);
751
+ })
752
+ ]
753
+ })
754
+ }), /* @__PURE__ */ jsx(ChartDataTable, {
755
+ caption: label,
756
+ indexHeader: index,
757
+ columns: resolvedSeries.map((s) => s.name ?? s.dataKey),
758
+ rows: data.map((row) => ({
759
+ label: String(row[index] ?? ""),
760
+ values: resolvedSeries.map((s) => formatChartValue(row[s.dataKey], valueFormatter))
761
+ }))
762
+ })]
763
+ });
764
+ });
765
+ RadarChart.displayName = "RadarChart";
766
+ //#endregion
767
+ //#region src/components/heatmap-grid.tsx
768
+ const MIN_TINT = .08;
769
+ const MAX_TINT = .9;
770
+ const AA = 4.5;
771
+ const WHITE = [
772
+ 255,
773
+ 255,
774
+ 255
775
+ ];
776
+ const BLACK = [
777
+ 0,
778
+ 0,
779
+ 0
780
+ ];
781
+ const formatPercent = (value) => `${Math.round(value)}%`;
782
+ /**
783
+ * The first candidate that reaches AA on `background`. Pure black or white
784
+ * always gets there (one of them is at least 4.58:1 on any color), so the
785
+ * printed value never drops below AA.
786
+ */
787
+ function readableText(background, preferred) {
788
+ const bg = rgbToHex(background);
789
+ for (const candidate of preferred) if (contrastRatio(rgbToHex(candidate), bg) >= AA) return candidate;
790
+ return contrastRatio("#000000", bg) >= contrastRatio("#ffffff", bg) ? BLACK : WHITE;
791
+ }
792
+ const HeatmapGrid = React.forwardRef(({ className, columns, rows, colors, max = 100, rowHeader = "Row", summary, valueFormatter = formatPercent, ...props }, ref) => {
793
+ const { setRef, colorAt, containerRef, themeVersion } = useChartColors(colors, ref);
794
+ const [palette, setPalette] = React.useState(null);
795
+ React.useEffect(() => {
796
+ const el = containerRef.current;
797
+ const surface = parseCssColor(resolveHslToken("--background", el));
798
+ const foreground = parseCssColor(resolveHslToken("--foreground", el));
799
+ setPalette({
800
+ surface: surface ?? WHITE,
801
+ foreground: foreground ?? BLACK
802
+ });
803
+ }, [containerRef, themeVersion]);
804
+ const label = chartLabel(summary, props, "Heatmap");
805
+ const cellStyle = (rowColor, value) => {
806
+ const share = Math.min(1, Math.max(0, max > 0 ? value / max : 0));
807
+ const tint = MIN_TINT + (MAX_TINT - MIN_TINT) * share;
808
+ const rgb = parseCssColor(rowColor);
809
+ if (!palette || !rgb) return {
810
+ backgroundColor: `color-mix(in srgb, ${rowColor} ${Math.round(tint * 100)}%, hsl(var(--background)))`,
811
+ color: "hsl(var(--foreground))"
812
+ };
813
+ const background = mixRgb(rgb, palette.surface, tint);
814
+ const text = readableText(background, [palette.foreground, palette.surface]);
815
+ return {
816
+ backgroundColor: rgbToHex(background),
817
+ color: rgbToHex(text)
818
+ };
819
+ };
820
+ return /* @__PURE__ */ jsx("div", {
821
+ ref: setRef,
822
+ className: cn("w-full overflow-x-auto", className),
823
+ ...props,
824
+ children: /* @__PURE__ */ jsxs("table", {
825
+ className: "w-full border-separate border-spacing-1 text-xs",
826
+ children: [
827
+ /* @__PURE__ */ jsx("caption", {
828
+ className: "sr-only",
829
+ children: label
830
+ }),
831
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
832
+ scope: "col",
833
+ className: "text-left font-normal",
834
+ children: /* @__PURE__ */ jsx("span", {
835
+ className: "sr-only",
836
+ children: rowHeader
837
+ })
838
+ }), columns.map((column) => /* @__PURE__ */ jsx("th", {
839
+ scope: "col",
840
+ className: "px-1 pb-1 text-center font-medium text-muted-foreground",
841
+ children: column
842
+ }, column))] }) }),
843
+ /* @__PURE__ */ jsx("tbody", { children: rows.map((row, r) => {
844
+ const rowColor = colorAt(r, row.color);
845
+ return /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
846
+ scope: "row",
847
+ className: "whitespace-nowrap pr-2 text-left font-medium text-muted-foreground",
848
+ children: row.label
849
+ }), columns.map((column, c) => {
850
+ const value = row.values[c];
851
+ if (typeof value !== "number" || !Number.isFinite(value)) return /* @__PURE__ */ jsxs("td", {
852
+ className: "rounded-sm border border-dashed border-border px-2 py-2 text-center text-muted-foreground",
853
+ children: [/* @__PURE__ */ jsx("span", {
854
+ "aria-hidden": "true",
855
+ children: "–"
856
+ }), /* @__PURE__ */ jsx("span", {
857
+ className: "sr-only",
858
+ children: "No data"
859
+ })]
860
+ }, column);
861
+ return /* @__PURE__ */ jsx("td", {
862
+ className: "rounded-sm px-2 py-2 text-center font-medium tabular-nums",
863
+ style: cellStyle(rowColor, value),
864
+ children: valueFormatter(value)
865
+ }, column);
866
+ })] }, `${row.label}-${r}`);
867
+ }) })
868
+ ]
869
+ })
870
+ });
871
+ });
872
+ HeatmapGrid.displayName = "HeatmapGrid";
271
873
  //#endregion
272
- export { AreaChart, BarChart, DonutChart, chartColorTokens, chartSizeMap, getThemeColors, resolveHslToken };
874
+ export { AreaChart, BarChart, DonutChart, HeatmapGrid, LineChart, RadarChart, chartColorTokens, chartSizeMap, getThemeColors, resolveHslToken };
273
875
 
274
876
  //# sourceMappingURL=charts.mjs.map