@reactloom/charts 0.0.0-stage → 1.0.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.
Files changed (51) hide show
  1. package/README.md +39 -2
  2. package/dist/LICENSE +21 -0
  3. package/dist/_internal/hooks/use-isomorphic-layout-effect.js +7 -0
  4. package/dist/_internal/hooks/use-isomorphic-layout-effect.js.map +1 -0
  5. package/dist/_internal/primitives/visually-hidden.js +29 -0
  6. package/dist/_internal/primitives/visually-hidden.js.map +1 -0
  7. package/dist/_internal/utils/cx.js +10 -0
  8. package/dist/_internal/utils/cx.js.map +1 -0
  9. package/dist/_internal/utils/warn.js +13 -0
  10. package/dist/_internal/utils/warn.js.map +1 -0
  11. package/dist/advanced-charts.d.ts +37 -0
  12. package/dist/advanced-charts.d.ts.map +1 -0
  13. package/dist/advanced-charts.js +587 -0
  14. package/dist/advanced-charts.js.map +1 -0
  15. package/dist/cartesian.d.ts +25 -0
  16. package/dist/cartesian.d.ts.map +1 -0
  17. package/dist/cartesian.js +461 -0
  18. package/dist/cartesian.js.map +1 -0
  19. package/dist/chart-frame.d.ts +55 -0
  20. package/dist/chart-frame.d.ts.map +1 -0
  21. package/dist/chart-frame.js +148 -0
  22. package/dist/chart-frame.js.map +1 -0
  23. package/dist/charts.d.ts +35 -0
  24. package/dist/charts.d.ts.map +1 -0
  25. package/dist/charts.js +47 -0
  26. package/dist/charts.js.map +1 -0
  27. package/dist/charts.module.js +126 -0
  28. package/dist/charts.module.js.map +1 -0
  29. package/dist/format.d.ts +42 -0
  30. package/dist/format.d.ts.map +1 -0
  31. package/dist/format.js +101 -0
  32. package/dist/format.js.map +1 -0
  33. package/dist/index.d.ts +7 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +6 -0
  36. package/dist/item-charts.d.ts +140 -0
  37. package/dist/item-charts.d.ts.map +1 -0
  38. package/dist/item-charts.js +1476 -0
  39. package/dist/item-charts.js.map +1 -0
  40. package/dist/pie-chart.d.ts +23 -0
  41. package/dist/pie-chart.d.ts.map +1 -0
  42. package/dist/pie-chart.js +216 -0
  43. package/dist/pie-chart.js.map +1 -0
  44. package/dist/sparkline.d.ts +25 -0
  45. package/dist/sparkline.d.ts.map +1 -0
  46. package/dist/sparkline.js +88 -0
  47. package/dist/sparkline.js.map +1 -0
  48. package/dist/styles.css +3 -0
  49. package/dist/types.d.ts +84 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/package.json +76 -3
@@ -0,0 +1,1476 @@
1
+ "use client";
2
+ import { ChartFrame, Legend, useKeyboardHint, useMeasuredRef, usePlotLayout } from "./chart-frame.js";
3
+ import { defaultMessages, read, seriesColor, useFormatters } from "./format.js";
4
+ import charts_module_default from "./charts.module.js";
5
+ import { useMemo, useState } from "react";
6
+ import { Table, useLocale } from "@reactloom/ui";
7
+ import { jsx, jsxs } from "react/jsx-runtime";
8
+ // src/item-charts.tsx
9
+ /** Arrow keys over `texts` (a grid when `columns` is given), announcing each item. */
10
+ function useExplorer(texts, columns) {
11
+ const [active, setActiveState] = useState(null);
12
+ const [announcement, setAnnouncement] = useState("");
13
+ const setActive = (index) => {
14
+ setActiveState(index);
15
+ if (index !== null && texts[index] !== void 0) setAnnouncement(texts[index] ?? "");
16
+ };
17
+ const onKeyDown = (event) => {
18
+ const n = texts.length;
19
+ if (!n) return;
20
+ const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
21
+ const current = active ?? -1;
22
+ const forward = event.key === (rtl ? "ArrowLeft" : "ArrowRight");
23
+ const back = event.key === (rtl ? "ArrowRight" : "ArrowLeft");
24
+ let next = null;
25
+ if (columns && columns > 1) {
26
+ const c = current < 0 ? 0 : current;
27
+ if (forward) next = current < 0 ? 0 : Math.min(n - 1, c + 1);
28
+ else if (back) next = Math.max(0, c - 1);
29
+ else if (event.key === "ArrowDown") next = current < 0 ? 0 : Math.min(n - 1, c + columns);
30
+ else if (event.key === "ArrowUp") next = Math.max(0, c - columns);
31
+ } else if (forward || event.key === "ArrowDown") next = (current + 1) % n;
32
+ else if (back || event.key === "ArrowUp") next = current < 0 ? n - 1 : (current - 1 + n) % n;
33
+ if (event.key === "Home") next = 0;
34
+ if (event.key === "End") next = n - 1;
35
+ if (event.key === "Escape" && active !== null) {
36
+ event.preventDefault();
37
+ setActiveState(null);
38
+ return;
39
+ }
40
+ if (next === null) return;
41
+ event.preventDefault();
42
+ setActive(next);
43
+ };
44
+ return {
45
+ active,
46
+ setActive,
47
+ announcement,
48
+ onKeyDown
49
+ };
50
+ }
51
+ /** The focusable plot: a group named by the title, with the SVG hidden from assistive tech. */
52
+ function Plot({ title, height, width, explorer, hint, tooltip, children }) {
53
+ return /* @__PURE__ */ jsxs("div", {
54
+ className: charts_module_default.plot,
55
+ role: "group",
56
+ "aria-label": title,
57
+ "aria-describedby": hint.id,
58
+ tabIndex: 0,
59
+ onKeyDown: explorer.onKeyDown,
60
+ onBlur: () => explorer.setActive(null),
61
+ children: [
62
+ hint.node,
63
+ /* @__PURE__ */ jsx("svg", {
64
+ "data-chart-plot": "",
65
+ className: charts_module_default.svg,
66
+ viewBox: `0 0 ${width} ${height}`,
67
+ width: "100%",
68
+ height,
69
+ "aria-hidden": "true",
70
+ focusable: "false",
71
+ onPointerLeave: () => explorer.setActive(null),
72
+ children
73
+ }),
74
+ tooltip ? /* @__PURE__ */ jsx("div", {
75
+ className: charts_module_default.tooltip,
76
+ "data-chart-tooltip": "",
77
+ "aria-hidden": "true",
78
+ style: tooltip.x > width / 2 ? {
79
+ right: `${width - tooltip.x + 12}px`,
80
+ top: tooltip.y
81
+ } : {
82
+ left: `${tooltip.x + 12}px`,
83
+ top: tooltip.y
84
+ },
85
+ children: tooltip.text
86
+ }) : null
87
+ ]
88
+ });
89
+ }
90
+ var Empty = ({ height, children }) => /* @__PURE__ */ jsx("div", {
91
+ className: charts_module_default.empty,
92
+ style: { height },
93
+ children
94
+ });
95
+ function useChart(props) {
96
+ const { locale } = useLocale();
97
+ const messages = {
98
+ ...defaultMessages,
99
+ ...props.messages
100
+ };
101
+ const format = useFormatters(locale, props);
102
+ const plotRef = useMeasuredRef();
103
+ const { width, rtl } = usePlotLayout(plotRef);
104
+ return {
105
+ locale,
106
+ messages,
107
+ format,
108
+ plotRef,
109
+ width,
110
+ rtl,
111
+ hint: useKeyboardHint(messages.keyboardHint)
112
+ };
113
+ }
114
+ var frameProps = (props, kind, messages, height) => ({
115
+ kind,
116
+ title: props.title,
117
+ hideTitle: props.hideTitle,
118
+ hideDescription: props.hideDescription,
119
+ loading: props.loading,
120
+ messages,
121
+ height,
122
+ className: props.className,
123
+ id: props.id
124
+ });
125
+ /** A sequential colour from the theme's first chart colour: light for low, strong for high. */
126
+ var sequential = (t) => `color-mix(in srgb, var(--pl-color-chart-1) ${Math.round(12 + Math.max(0, Math.min(1, t)) * 83)}%, var(--pl-color-bg-surface))`;
127
+ /** Values across two categories (weekday × hour, team × metric) as a colour grid. Arrow keys move in two dimensions. */
128
+ function Heatmap(props) {
129
+ const { data, title, height = 280, table = "toggle", emptyState, showValues = false } = props;
130
+ const { messages, format, plotRef, width, rtl, hint } = useChart(props);
131
+ const xs = [...new Set(data.map((r) => String(read(props.x, r))))];
132
+ const ys = [...new Set(data.map((r) => String(read(props.y, r))))];
133
+ const cell = new Map(data.map((r) => [`${read(props.y, r)}\u0000${read(props.x, r)}`, read(props.value, r)]));
134
+ const values = [...cell.values()].filter((v) => typeof v === "number" && Number.isFinite(v));
135
+ const [lo, hi] = props.domain ?? [Math.min(...values), Math.max(...values)];
136
+ const t = (v) => hi === lo ? 1 : (v - lo) / (hi - lo);
137
+ const grid = ys.flatMap((y) => xs.map((x) => ({
138
+ x,
139
+ y,
140
+ value: cell.get(`${y}\u0000${x}`)
141
+ })));
142
+ const texts = grid.map((c) => `${c.y}, ${c.x}: ${typeof c.value === "number" ? format.value(c.value) : "—"}`);
143
+ const explorer = useExplorer(texts, xs.length);
144
+ const left = Math.min(120, Math.max(48, Math.max(...ys.map((y) => y.length)) * 7 + 12));
145
+ const top = 22;
146
+ const cw = Math.max(8, (width - left - 4) / Math.max(1, xs.length));
147
+ const ch = Math.max(8, (height - top - 4) / Math.max(1, ys.length));
148
+ const px = (i) => rtl ? width - left - (i + 1) * cw : left + i * cw;
149
+ const empty = values.length === 0;
150
+ const summary = props.description ?? (empty ? "" : `Heatmap of ${ys.length} rows by ${xs.length} columns, values from ${format.value(lo)} to ${format.value(hi)}. Highest: ${texts[grid.findIndex((c) => c.value === Math.max(...values))]}.`);
151
+ const active = explorer.active === null ? null : grid[explorer.active];
152
+ const renderTable = () => {
153
+ const rows = ys.map((y) => ({
154
+ y,
155
+ ...Object.fromEntries(xs.map((x) => [x, cell.get(`${y}\u0000${x}`)]))
156
+ }));
157
+ const columns = [{
158
+ key: "y",
159
+ header: messages.categoryHeader,
160
+ rowHeader: true
161
+ }, ...xs.map((x) => ({
162
+ key: x,
163
+ header: x,
164
+ align: "end",
165
+ cell: (r) => typeof r[x] === "number" ? format.value(r[x]) : "—"
166
+ }))];
167
+ return /* @__PURE__ */ jsx(Table, {
168
+ columns,
169
+ rows,
170
+ getRowId: (r) => r.y,
171
+ caption: messages.tableCaption(title),
172
+ density: "compact"
173
+ });
174
+ };
175
+ return /* @__PURE__ */ jsx(ChartFrame, {
176
+ ...frameProps(props, "heatmap", messages, height),
177
+ description: summary,
178
+ table: empty ? "none" : table,
179
+ renderTable,
180
+ announcement: explorer.announcement,
181
+ legend: empty ? void 0 : /* @__PURE__ */ jsxs("div", {
182
+ className: charts_module_default.scale,
183
+ "aria-hidden": "true",
184
+ children: [
185
+ /* @__PURE__ */ jsx("span", { children: format.value(lo) }),
186
+ /* @__PURE__ */ jsx("span", {
187
+ className: charts_module_default.scaleBar,
188
+ style: { background: `linear-gradient(to right, ${sequential(0)}, ${sequential(1)})` }
189
+ }),
190
+ /* @__PURE__ */ jsx("span", { children: format.value(hi) })
191
+ ]
192
+ }),
193
+ children: /* @__PURE__ */ jsx("div", {
194
+ ref: plotRef,
195
+ className: charts_module_default.plotWrap,
196
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
197
+ height,
198
+ children: emptyState ?? messages.empty
199
+ }) : /* @__PURE__ */ jsxs(Plot, {
200
+ title,
201
+ height,
202
+ width,
203
+ explorer,
204
+ hint,
205
+ tooltip: active ? {
206
+ text: texts[explorer.active ?? 0] ?? "",
207
+ x: px(xs.indexOf(active.x)) + cw / 2,
208
+ y: top + ys.indexOf(active.y) * ch
209
+ } : null,
210
+ children: [
211
+ xs.map((x, i) => /* @__PURE__ */ jsx("text", {
212
+ x: px(i) + cw / 2,
213
+ y: 14,
214
+ className: charts_module_default.tickLabel,
215
+ textAnchor: "middle",
216
+ children: cw > 28 || i % Math.ceil(28 / cw) === 0 ? x : ""
217
+ }, x)),
218
+ ys.map((y, j) => /* @__PURE__ */ jsx("text", {
219
+ x: rtl ? width - left + 6 : left - 6,
220
+ y: top + j * ch + ch / 2 + 4,
221
+ className: charts_module_default.tickLabel,
222
+ textAnchor: rtl ? "start" : "end",
223
+ children: y
224
+ }, y)),
225
+ grid.map((c, k) => {
226
+ const i = xs.indexOf(c.x);
227
+ const j = ys.indexOf(c.y);
228
+ const v = typeof c.value === "number" ? c.value : null;
229
+ return /* @__PURE__ */ jsxs("g", {
230
+ onPointerEnter: () => explorer.setActive(k),
231
+ children: [/* @__PURE__ */ jsx("rect", {
232
+ x: px(i) + 1,
233
+ y: top + j * ch + 1,
234
+ width: cw - 2,
235
+ height: ch - 2,
236
+ rx: 2,
237
+ fill: v === null ? "var(--pl-color-bg-subtle)" : sequential(t(v)),
238
+ className: charts_module_default.cell,
239
+ "data-active": explorer.active === k || void 0
240
+ }), showValues && v !== null && cw > 34 && ch > 16 ? /* @__PURE__ */ jsx("text", {
241
+ x: px(i) + cw / 2,
242
+ y: top + j * ch + ch / 2 + 4,
243
+ textAnchor: "middle",
244
+ className: t(v) > .55 ? charts_module_default.cellTextStrong : charts_module_default.cellText,
245
+ children: format.tick(v)
246
+ }) : null]
247
+ }, k);
248
+ })
249
+ ]
250
+ })
251
+ })
252
+ });
253
+ }
254
+ /** The distribution of one measure: values counted into equal-width bins. */
255
+ function Histogram(props) {
256
+ const { values, title, height = 260, table = "toggle", emptyState, countLabel = "Count" } = props;
257
+ const { messages, format, plotRef, width, rtl, hint } = useChart(props);
258
+ const finite = values.filter((v) => Number.isFinite(v));
259
+ const binsData = useMemo(() => {
260
+ if (!finite.length) return [];
261
+ const min = Math.min(...finite);
262
+ const max = Math.max(...finite);
263
+ const n = Math.max(1, props.bins ?? Math.ceil(Math.log2(finite.length) + 1));
264
+ const size = max === min ? 1 : (max - min) / n;
265
+ const out = Array.from({ length: n }, (_, i) => ({
266
+ from: min + i * size,
267
+ to: min + (i + 1) * size,
268
+ count: 0
269
+ }));
270
+ for (const v of finite) {
271
+ const bin = out[Math.min(n - 1, Math.floor((v - min) / size))];
272
+ if (bin) bin.count++;
273
+ }
274
+ return out;
275
+ }, [values, props.bins]);
276
+ const label = (b) => `${format.value(b.from)}–${format.value(b.to)}`;
277
+ const texts = binsData.map((b) => `${label(b)}: ${b.count}`);
278
+ const explorer = useExplorer(texts);
279
+ const peak = Math.max(1, ...binsData.map((b) => b.count));
280
+ const left = 36;
281
+ const bottom = 22;
282
+ const bw = (width - left - 4) / Math.max(1, binsData.length);
283
+ const bx = (i) => rtl ? width - left - (i + 1) * bw : left + i * bw;
284
+ const y = (c) => (height - bottom) * (1 - c / peak) + 4;
285
+ const empty = binsData.length === 0;
286
+ const mode = binsData.reduce((best, b) => b.count > best.count ? b : best, binsData[0] ?? {
287
+ from: 0,
288
+ to: 0,
289
+ count: 0
290
+ });
291
+ const summary = props.description ?? (empty ? "" : `Histogram of ${finite.length} values from ${format.value(Math.min(...finite))} to ${format.value(Math.max(...finite))} in ${binsData.length} bins. Most values fall in ${label(mode)} (${mode.count}).`);
292
+ const renderTable = () => {
293
+ const columns = [{
294
+ key: "range",
295
+ header: messages.categoryHeader,
296
+ rowHeader: true
297
+ }, {
298
+ key: "count",
299
+ header: countLabel,
300
+ align: "end"
301
+ }];
302
+ return /* @__PURE__ */ jsx(Table, {
303
+ columns,
304
+ rows: binsData.map((b, i) => ({
305
+ i,
306
+ range: label(b),
307
+ count: b.count
308
+ })),
309
+ getRowId: (r) => String(r.i),
310
+ caption: messages.tableCaption(title),
311
+ density: "compact"
312
+ });
313
+ };
314
+ const a = explorer.active === null ? null : binsData[explorer.active];
315
+ return /* @__PURE__ */ jsx(ChartFrame, {
316
+ ...frameProps(props, "histogram", messages, height),
317
+ description: summary,
318
+ table: empty ? "none" : table,
319
+ renderTable,
320
+ announcement: explorer.announcement,
321
+ children: /* @__PURE__ */ jsx("div", {
322
+ ref: plotRef,
323
+ className: charts_module_default.plotWrap,
324
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
325
+ height,
326
+ children: emptyState ?? messages.empty
327
+ }) : /* @__PURE__ */ jsxs(Plot, {
328
+ title,
329
+ height,
330
+ width,
331
+ explorer,
332
+ hint,
333
+ tooltip: a && explorer.active !== null ? {
334
+ text: texts[explorer.active] ?? "",
335
+ x: bx(explorer.active) + bw / 2,
336
+ y: y(a.count)
337
+ } : null,
338
+ children: [
339
+ [
340
+ 0,
341
+ .5,
342
+ 1
343
+ ].map((f) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
344
+ x1: left,
345
+ x2: width,
346
+ y1: y(peak * f),
347
+ y2: y(peak * f),
348
+ className: charts_module_default.gridLine
349
+ }), /* @__PURE__ */ jsx("text", {
350
+ x: rtl ? width - 4 : 4,
351
+ y: y(peak * f) + 4,
352
+ className: charts_module_default.tickLabel,
353
+ textAnchor: rtl ? "end" : "start",
354
+ children: Math.round(peak * f)
355
+ })] }, f)),
356
+ binsData.map((b, i) => /* @__PURE__ */ jsx("rect", {
357
+ x: bx(i) + 1,
358
+ y: y(b.count),
359
+ width: Math.max(1, bw - 2),
360
+ height: height - bottom + 4 - y(b.count),
361
+ fill: seriesColor(0),
362
+ className: charts_module_default.bar,
363
+ "data-active": explorer.active === i || void 0,
364
+ onPointerEnter: () => explorer.setActive(i)
365
+ }, i)),
366
+ binsData.map((b, i) => i % Math.ceil(binsData.length / 6) === 0 ? /* @__PURE__ */ jsx("text", {
367
+ x: bx(i) + (rtl ? bw : 0),
368
+ y: height - 6,
369
+ className: charts_module_default.tickLabel,
370
+ textAnchor: "start",
371
+ children: format.tick(b.from)
372
+ }, `t${i}`) : null)
373
+ ]
374
+ })
375
+ })
376
+ });
377
+ }
378
+ /** Quartile (type 7, as in spreadsheets) of sorted values. */
379
+ function quantile(sorted, q) {
380
+ const pos = (sorted.length - 1) * q;
381
+ const base = Math.floor(pos);
382
+ const next = sorted[base + 1];
383
+ const here = sorted[base] ?? 0;
384
+ return next === void 0 ? here : here + (pos - base) * (next - here);
385
+ }
386
+ function boxStats(label, values) {
387
+ const s = values.filter(Number.isFinite).slice().sort((a, b) => a - b);
388
+ const q1 = quantile(s, .25);
389
+ const q3 = quantile(s, .75);
390
+ const fence = 1.5 * (q3 - q1);
391
+ const inside = s.filter((v) => v >= q1 - fence && v <= q3 + fence);
392
+ return {
393
+ label,
394
+ q1,
395
+ q3,
396
+ median: quantile(s, .5),
397
+ min: inside[0] ?? q1,
398
+ max: inside.at(-1) ?? q3,
399
+ outliers: s.filter((v) => v < q1 - fence || v > q3 + fence),
400
+ count: s.length
401
+ };
402
+ }
403
+ /** Compares distributions: median, quartiles, whiskers (1.5 × IQR) and outliers per group. */
404
+ function BoxPlot(props) {
405
+ const { data, title, height = 280, table = "toggle", emptyState } = props;
406
+ const { messages, format, plotRef, width, rtl, hint } = useChart(props);
407
+ const stats = data.map((r) => boxStats(String(read(props.label, r)), read(props.values, r))).filter((s) => s.count > 0);
408
+ const describe = (s) => `${s.label}: median ${format.value(s.median)}, quartiles ${format.value(s.q1)} to ${format.value(s.q3)}, range ${format.value(s.min)} to ${format.value(s.max)}${s.outliers.length ? `, ${s.outliers.length} outliers` : ""}`;
409
+ const texts = stats.map(describe);
410
+ const explorer = useExplorer(texts);
411
+ const all = stats.flatMap((s) => [
412
+ s.min,
413
+ s.max,
414
+ ...s.outliers
415
+ ]);
416
+ const lo = Math.min(...all);
417
+ const hi = Math.max(...all);
418
+ const left = 44;
419
+ const bottom = 24;
420
+ const y = (v) => 6 + (height - bottom - 12) * (1 - (hi === lo ? .5 : (v - lo) / (hi - lo)));
421
+ const bw = (width - left) / Math.max(1, stats.length);
422
+ const cxOf = (i) => rtl ? width - left - (i + .5) * bw : left + (i + .5) * bw;
423
+ const empty = stats.length === 0;
424
+ const summary = props.description ?? (empty ? "" : `Box plot of ${stats.length} groups. ${texts.slice(0, 3).join("; ")}.`);
425
+ const renderTable = () => {
426
+ const col = (key, header) => ({
427
+ key,
428
+ header,
429
+ align: "end",
430
+ cell: (s) => format.value(s[key])
431
+ });
432
+ const columns = [
433
+ {
434
+ key: "label",
435
+ header: messages.categoryHeader,
436
+ rowHeader: true
437
+ },
438
+ col("min", "Min"),
439
+ col("q1", "Q1"),
440
+ col("median", "Median"),
441
+ col("q3", "Q3"),
442
+ col("max", "Max"),
443
+ {
444
+ key: "outliers",
445
+ header: "Outliers",
446
+ cell: (s) => s.outliers.map(format.value).join(", ")
447
+ }
448
+ ];
449
+ return /* @__PURE__ */ jsx(Table, {
450
+ columns,
451
+ rows: stats,
452
+ getRowId: (s) => s.label,
453
+ caption: messages.tableCaption(title),
454
+ density: "compact"
455
+ });
456
+ };
457
+ return /* @__PURE__ */ jsx(ChartFrame, {
458
+ ...frameProps(props, "box", messages, height),
459
+ description: summary,
460
+ table: empty ? "none" : table,
461
+ renderTable,
462
+ announcement: explorer.announcement,
463
+ children: /* @__PURE__ */ jsx("div", {
464
+ ref: plotRef,
465
+ className: charts_module_default.plotWrap,
466
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
467
+ height,
468
+ children: emptyState ?? messages.empty
469
+ }) : /* @__PURE__ */ jsxs(Plot, {
470
+ title,
471
+ height,
472
+ width,
473
+ explorer,
474
+ hint,
475
+ tooltip: explorer.active !== null && stats[explorer.active] ? {
476
+ text: texts[explorer.active] ?? "",
477
+ x: cxOf(explorer.active),
478
+ y: y(stats[explorer.active]?.q3 ?? 0)
479
+ } : null,
480
+ children: [[
481
+ lo,
482
+ (lo + hi) / 2,
483
+ hi
484
+ ].map((v, i) => /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("line", {
485
+ x1: left,
486
+ x2: width,
487
+ y1: y(v),
488
+ y2: y(v),
489
+ className: charts_module_default.gridLine
490
+ }), /* @__PURE__ */ jsx("text", {
491
+ x: rtl ? width - 4 : 4,
492
+ y: y(v) + 4,
493
+ className: charts_module_default.tickLabel,
494
+ textAnchor: rtl ? "end" : "start",
495
+ children: format.tick(v)
496
+ })] }, i)), stats.map((s, i) => {
497
+ const c = cxOf(i);
498
+ const w = Math.min(48, bw * .5);
499
+ const color = seriesColor(i);
500
+ return /* @__PURE__ */ jsxs("g", {
501
+ className: charts_module_default.box,
502
+ "data-active": explorer.active === i || void 0,
503
+ onPointerEnter: () => explorer.setActive(i),
504
+ children: [
505
+ /* @__PURE__ */ jsx("line", {
506
+ x1: c,
507
+ x2: c,
508
+ y1: y(s.max),
509
+ y2: y(s.q3),
510
+ stroke: color,
511
+ className: charts_module_default.whisker
512
+ }),
513
+ /* @__PURE__ */ jsx("line", {
514
+ x1: c,
515
+ x2: c,
516
+ y1: y(s.q1),
517
+ y2: y(s.min),
518
+ stroke: color,
519
+ className: charts_module_default.whisker
520
+ }),
521
+ /* @__PURE__ */ jsx("line", {
522
+ x1: c - w / 4,
523
+ x2: c + w / 4,
524
+ y1: y(s.max),
525
+ y2: y(s.max),
526
+ stroke: color,
527
+ className: charts_module_default.whisker
528
+ }),
529
+ /* @__PURE__ */ jsx("line", {
530
+ x1: c - w / 4,
531
+ x2: c + w / 4,
532
+ y1: y(s.min),
533
+ y2: y(s.min),
534
+ stroke: color,
535
+ className: charts_module_default.whisker
536
+ }),
537
+ /* @__PURE__ */ jsx("rect", {
538
+ x: c - w / 2,
539
+ y: y(s.q3),
540
+ width: w,
541
+ height: Math.max(1, y(s.q1) - y(s.q3)),
542
+ fill: `color-mix(in srgb, ${color} 25%, var(--pl-color-bg-surface))`,
543
+ stroke: color,
544
+ rx: 2
545
+ }),
546
+ /* @__PURE__ */ jsx("line", {
547
+ x1: c - w / 2,
548
+ x2: c + w / 2,
549
+ y1: y(s.median),
550
+ y2: y(s.median),
551
+ stroke: color,
552
+ strokeWidth: 2.5
553
+ }),
554
+ s.outliers.map((o, k) => /* @__PURE__ */ jsx("circle", {
555
+ cx: c,
556
+ cy: y(o),
557
+ r: 3,
558
+ fill: "none",
559
+ stroke: color
560
+ }, k)),
561
+ /* @__PURE__ */ jsx("text", {
562
+ x: c,
563
+ y: height - 6,
564
+ className: charts_module_default.tickLabel,
565
+ textAnchor: "middle",
566
+ children: s.label
567
+ })
568
+ ]
569
+ }, s.label);
570
+ })]
571
+ })
572
+ })
573
+ });
574
+ }
575
+ /** How a starting value becomes an end value through increases and decreases. */
576
+ function WaterfallChart(props) {
577
+ const { data, title, height = 280, table = "toggle", emptyState, isTotal } = props;
578
+ const { messages, format, plotRef, width, rtl, hint } = useChart(props);
579
+ const words = {
580
+ increase: "increase",
581
+ decrease: "decrease",
582
+ total: "total",
583
+ ...props.messages
584
+ };
585
+ const steps = data.reduce((list, r, index) => {
586
+ const before = list.at(-1)?.to ?? 0;
587
+ const total = Boolean(isTotal?.(r));
588
+ const change = total ? 0 : Number(read(props.value, r)) || 0;
589
+ return [...list, {
590
+ index,
591
+ label: String(read(props.label, r)),
592
+ total,
593
+ change,
594
+ from: total ? 0 : before,
595
+ to: total ? before : before + change
596
+ }];
597
+ }, []);
598
+ const running = steps.at(-1)?.to ?? 0;
599
+ const describe = (s) => s.total ? `${s.label}: ${words.total} ${format.value(s.to)}` : `${s.label}: ${s.change >= 0 ? words.increase : words.decrease} of ${format.value(Math.abs(s.change))}, running total ${format.value(s.to)}`;
600
+ const texts = steps.map(describe);
601
+ const explorer = useExplorer(texts);
602
+ const values = steps.flatMap((s) => [
603
+ s.from,
604
+ s.to,
605
+ 0
606
+ ]);
607
+ const lo = Math.min(...values);
608
+ const hi = Math.max(...values);
609
+ const left = 44;
610
+ const bottom = 24;
611
+ const y = (v) => 6 + (height - bottom - 12) * (1 - (hi === lo ? .5 : (v - lo) / (hi - lo)));
612
+ const bw = (width - left) / Math.max(1, steps.length);
613
+ const bx = (i) => rtl ? width - left - (i + 1) * bw : left + i * bw;
614
+ const fill = (s) => s.total ? "var(--pl-color-fg-muted)" : s.change >= 0 ? "var(--pl-color-success-solid)" : "var(--pl-color-danger-solid)";
615
+ const empty = steps.length === 0;
616
+ const summary = props.description ?? (empty ? "" : `Waterfall chart of ${steps.length} steps, ending at ${format.value(running)}.`);
617
+ const renderTable = () => {
618
+ const columns = [
619
+ {
620
+ key: "label",
621
+ header: messages.categoryHeader,
622
+ rowHeader: true
623
+ },
624
+ {
625
+ key: "change",
626
+ header: "Change",
627
+ align: "end",
628
+ cell: (s) => s.total ? "" : `${s.change >= 0 ? "+" : "−"}${format.value(Math.abs(s.change))}`
629
+ },
630
+ {
631
+ key: "to",
632
+ header: "Running total",
633
+ align: "end",
634
+ cell: (s) => format.value(s.to)
635
+ }
636
+ ];
637
+ return /* @__PURE__ */ jsx(Table, {
638
+ columns,
639
+ rows: steps,
640
+ getRowId: (s) => String(s.index),
641
+ caption: messages.tableCaption(title),
642
+ density: "compact"
643
+ });
644
+ };
645
+ return /* @__PURE__ */ jsx(ChartFrame, {
646
+ ...frameProps(props, "waterfall", messages, height),
647
+ description: summary,
648
+ table: empty ? "none" : table,
649
+ renderTable,
650
+ announcement: explorer.announcement,
651
+ legend: empty ? void 0 : /* @__PURE__ */ jsx(Legend, {
652
+ label: `${title}: legend`,
653
+ items: [
654
+ {
655
+ key: "up",
656
+ label: words.increase,
657
+ color: "var(--pl-color-success-solid)"
658
+ },
659
+ {
660
+ key: "down",
661
+ label: words.decrease,
662
+ color: "var(--pl-color-danger-solid)"
663
+ },
664
+ {
665
+ key: "total",
666
+ label: words.total,
667
+ color: "var(--pl-color-fg-muted)"
668
+ }
669
+ ]
670
+ }),
671
+ children: /* @__PURE__ */ jsx("div", {
672
+ ref: plotRef,
673
+ className: charts_module_default.plotWrap,
674
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
675
+ height,
676
+ children: emptyState ?? messages.empty
677
+ }) : /* @__PURE__ */ jsxs(Plot, {
678
+ title,
679
+ height,
680
+ width,
681
+ explorer,
682
+ hint,
683
+ tooltip: explorer.active !== null && steps[explorer.active] ? {
684
+ text: texts[explorer.active] ?? "",
685
+ x: bx(explorer.active) + bw / 2,
686
+ y: y(Math.max(steps[explorer.active]?.from ?? 0, steps[explorer.active]?.to ?? 0))
687
+ } : null,
688
+ children: [
689
+ /* @__PURE__ */ jsx("line", {
690
+ x1: left,
691
+ x2: width,
692
+ y1: y(0),
693
+ y2: y(0),
694
+ className: charts_module_default.axisLine
695
+ }),
696
+ [lo, hi].map((v, i) => /* @__PURE__ */ jsx("text", {
697
+ x: rtl ? width - 4 : 4,
698
+ y: y(v) + 4,
699
+ className: charts_module_default.tickLabel,
700
+ textAnchor: rtl ? "end" : "start",
701
+ children: format.tick(v)
702
+ }, i)),
703
+ steps.map((s, i) => {
704
+ const top = y(Math.max(s.from, s.to));
705
+ const h = Math.max(1, Math.abs(y(s.from) - y(s.to)));
706
+ return /* @__PURE__ */ jsxs("g", {
707
+ onPointerEnter: () => explorer.setActive(i),
708
+ children: [
709
+ /* @__PURE__ */ jsx("rect", {
710
+ x: bx(i) + bw * .15,
711
+ y: top,
712
+ width: bw * .7,
713
+ height: h,
714
+ fill: fill(s),
715
+ rx: 2,
716
+ className: charts_module_default.bar,
717
+ "data-active": explorer.active === i || void 0
718
+ }),
719
+ i < steps.length - 1 ? /* @__PURE__ */ jsx("line", {
720
+ x1: bx(i) + (rtl ? bw * .15 : bw * .85),
721
+ x2: bx(i + 1) + (rtl ? bw * .85 : bw * .15),
722
+ y1: y(s.to),
723
+ y2: y(s.to),
724
+ className: charts_module_default.connector
725
+ }) : null,
726
+ /* @__PURE__ */ jsx("text", {
727
+ x: bx(i) + bw / 2,
728
+ y: height - 6,
729
+ className: charts_module_default.tickLabel,
730
+ textAnchor: "middle",
731
+ children: s.label
732
+ })
733
+ ]
734
+ }, s.index);
735
+ })
736
+ ]
737
+ })
738
+ })
739
+ });
740
+ }
741
+ /** Stages of a process (visits → sign-ups → purchases) with the conversion between them. */
742
+ function FunnelChart(props) {
743
+ const { data, title, height = 260, table = "toggle", emptyState } = props;
744
+ const { messages, format, plotRef, width, hint } = useChart(props);
745
+ const stages = data.map((r, index) => ({
746
+ index,
747
+ label: String(read(props.label, r)),
748
+ value: Math.max(0, Number(read(props.value, r)) || 0)
749
+ }));
750
+ const first = stages[0]?.value ?? 0;
751
+ const rows = stages.map((s, i) => ({
752
+ ...s,
753
+ ofFirst: first ? s.value / first : 0,
754
+ ofPrevious: i === 0 ? 1 : stages[i - 1]?.value ?? 0 ? s.value / (stages[i - 1]?.value ?? 1) : 0
755
+ }));
756
+ const texts = rows.map((s, i) => `${s.label}: ${format.value(s.value)}${i ? `, ${format.percent(s.ofPrevious)} of ${rows[i - 1]?.label}, ${format.percent(s.ofFirst)} of ${rows[0]?.label}` : ""}`);
757
+ const explorer = useExplorer(texts);
758
+ const max = Math.max(1, ...rows.map((s) => s.value));
759
+ const rh = (height - 8) / Math.max(1, rows.length);
760
+ const labelW = Math.min(180, width * .32);
761
+ const plotW = width - labelW - 8;
762
+ const empty = rows.length === 0 || first === 0;
763
+ const last = rows.at(-1);
764
+ const summary = props.description ?? (empty || !last ? "" : `Funnel of ${rows.length} stages from ${format.value(first)} ${rows[0]?.label} to ${format.value(last.value)} ${last.label} (${format.percent(last.ofFirst)} overall).`);
765
+ const renderTable = () => {
766
+ const columns = [
767
+ {
768
+ key: "label",
769
+ header: messages.categoryHeader,
770
+ rowHeader: true
771
+ },
772
+ {
773
+ key: "value",
774
+ header: title,
775
+ align: "end",
776
+ cell: (s) => format.value(s.value)
777
+ },
778
+ {
779
+ key: "ofPrevious",
780
+ header: "Of previous",
781
+ align: "end",
782
+ cell: (s) => format.percent(s.ofPrevious)
783
+ },
784
+ {
785
+ key: "ofFirst",
786
+ header: "Of first",
787
+ align: "end",
788
+ cell: (s) => format.percent(s.ofFirst)
789
+ }
790
+ ];
791
+ return /* @__PURE__ */ jsx(Table, {
792
+ columns,
793
+ rows,
794
+ getRowId: (s) => String(s.index),
795
+ caption: messages.tableCaption(title),
796
+ density: "compact"
797
+ });
798
+ };
799
+ return /* @__PURE__ */ jsx(ChartFrame, {
800
+ ...frameProps(props, "funnel", messages, height),
801
+ description: summary,
802
+ table: empty ? "none" : table,
803
+ renderTable,
804
+ announcement: explorer.announcement,
805
+ children: /* @__PURE__ */ jsx("div", {
806
+ ref: plotRef,
807
+ className: charts_module_default.plotWrap,
808
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
809
+ height,
810
+ children: emptyState ?? messages.empty
811
+ }) : /* @__PURE__ */ jsx(Plot, {
812
+ title,
813
+ height,
814
+ width,
815
+ explorer,
816
+ hint,
817
+ tooltip: explorer.active !== null ? {
818
+ text: texts[explorer.active] ?? "",
819
+ x: labelW + plotW / 2,
820
+ y: explorer.active * rh
821
+ } : null,
822
+ children: rows.map((s, i) => {
823
+ const w = Math.max(2, s.value / max * plotW);
824
+ const x = labelW + (plotW - w) / 2;
825
+ return /* @__PURE__ */ jsxs("g", {
826
+ onPointerEnter: () => explorer.setActive(i),
827
+ children: [
828
+ /* @__PURE__ */ jsx("text", {
829
+ x: labelW - 8,
830
+ y: i * rh + rh / 2 + 4,
831
+ className: charts_module_default.tickLabel,
832
+ textAnchor: "end",
833
+ children: s.label
834
+ }),
835
+ /* @__PURE__ */ jsx("rect", {
836
+ x,
837
+ y: i * rh + 3,
838
+ width: w,
839
+ height: rh - 6,
840
+ rx: 3,
841
+ fill: seriesColor(0),
842
+ opacity: 1 - i * (.5 / Math.max(1, rows.length)),
843
+ className: charts_module_default.bar,
844
+ "data-active": explorer.active === i || void 0
845
+ }),
846
+ /* @__PURE__ */ jsxs("text", {
847
+ x: labelW + plotW / 2,
848
+ y: i * rh + rh / 2 + 4,
849
+ className: charts_module_default.barValue,
850
+ textAnchor: "middle",
851
+ children: [format.tick(s.value), i ? ` · ${format.percent(s.ofPrevious)}` : ""]
852
+ })
853
+ ]
854
+ }, s.index);
855
+ })
856
+ })
857
+ })
858
+ });
859
+ }
860
+ /** A single value against its range, as a half-circle meter (`role="meter"`). */
861
+ function Gauge(props) {
862
+ const { value, min = 0, max = 100, bands = [], title, height = 180 } = props;
863
+ const { messages, format, plotRef, width } = useChart(props);
864
+ const clamped = Math.min(max, Math.max(min, value));
865
+ const t = max === min ? 0 : (clamped - min) / (max - min);
866
+ const band = bands.find((b) => clamped <= b.to);
867
+ const text = `${format.value(value)}${band ? `, ${band.label}` : ""}`;
868
+ const r = Math.max(30, Math.min(width / 2 - 8, height - 24));
869
+ const cx = width / 2;
870
+ const cy = height - 12;
871
+ const point = (f, radius = r) => [cx - radius * Math.cos(Math.PI * f), cy - radius * Math.sin(Math.PI * f)];
872
+ const arc = (from, to) => {
873
+ const [x1, y1] = point(from);
874
+ const [x2, y2] = point(to);
875
+ return `M${x1},${y1} A${r},${r} 0 0 1 ${x2},${y2}`;
876
+ };
877
+ const fraction = (v) => max === min ? 0 : (Math.min(max, Math.max(min, v)) - min) / (max - min);
878
+ const [nx, ny] = point(t, r - 10);
879
+ const summary = props.description ?? `${text} on a scale from ${format.value(min)} to ${format.value(max)}.`;
880
+ return /* @__PURE__ */ jsx(ChartFrame, {
881
+ ...frameProps(props, "gauge", messages, height),
882
+ description: summary,
883
+ table: "none",
884
+ renderTable: () => null,
885
+ children: /* @__PURE__ */ jsx("div", {
886
+ ref: plotRef,
887
+ className: charts_module_default.plotWrap,
888
+ children: /* @__PURE__ */ jsxs("div", {
889
+ className: charts_module_default.gauge,
890
+ role: "meter",
891
+ "aria-label": title,
892
+ "aria-valuenow": value,
893
+ "aria-valuemin": min,
894
+ "aria-valuemax": max,
895
+ "aria-valuetext": text,
896
+ children: [/* @__PURE__ */ jsxs("svg", {
897
+ "data-chart-plot": "",
898
+ className: charts_module_default.svg,
899
+ viewBox: `0 0 ${width} ${height}`,
900
+ width: "100%",
901
+ height,
902
+ "aria-hidden": "true",
903
+ focusable: "false",
904
+ children: [
905
+ /* @__PURE__ */ jsx("path", {
906
+ d: arc(0, 1),
907
+ className: charts_module_default.gaugeTrack
908
+ }),
909
+ bands.map((b, i) => /* @__PURE__ */ jsx("path", {
910
+ d: arc(fraction(i ? bands[i - 1]?.to ?? min : min), fraction(b.to)),
911
+ stroke: b.color ?? seriesColor(i),
912
+ className: charts_module_default.gaugeBand
913
+ }, b.label)),
914
+ /* @__PURE__ */ jsx("path", {
915
+ d: arc(0, Math.max(.001, t)),
916
+ className: charts_module_default.gaugeValue
917
+ }),
918
+ /* @__PURE__ */ jsx("line", {
919
+ x1: cx,
920
+ y1: cy,
921
+ x2: nx,
922
+ y2: ny,
923
+ className: charts_module_default.gaugeNeedle
924
+ }),
925
+ /* @__PURE__ */ jsx("circle", {
926
+ cx,
927
+ cy,
928
+ r: 5,
929
+ className: charts_module_default.gaugeHub
930
+ }),
931
+ /* @__PURE__ */ jsx("text", {
932
+ x: cx,
933
+ y: cy - r / 2.6,
934
+ textAnchor: "middle",
935
+ className: charts_module_default.gaugeText,
936
+ children: format.value(value)
937
+ })
938
+ ]
939
+ }), band ? /* @__PURE__ */ jsx("span", {
940
+ className: charts_module_default.gaugeBandLabel,
941
+ children: band.label
942
+ }) : null]
943
+ })
944
+ })
945
+ });
946
+ }
947
+ /** Several measures per series on spokes around a centre (skills, product attributes). */
948
+ function RadarChart(props) {
949
+ const { data, series, title, height = 300, table = "toggle", emptyState } = props;
950
+ const { messages, format, plotRef, width, rtl, hint } = useChart(props);
951
+ const cats = data.map((r) => String(read(props.category, r)));
952
+ const val = (s, r) => {
953
+ const v = s.value ? s.value(r) : r[s.key];
954
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
955
+ };
956
+ const max = props.max ?? Math.max(1, ...data.flatMap((r) => series.map((s) => val(s, r))));
957
+ const texts = data.map((r, i) => `${cats[i]}: ${series.map((s) => `${s.label} ${format.value(val(s, r))}`).join(", ")}`);
958
+ const explorer = useExplorer(texts);
959
+ const radius = Math.max(30, Math.min(width, height) / 2 - 36);
960
+ const cx = width / 2;
961
+ const cy = height / 2;
962
+ const angle = (i) => (rtl ? -1 : 1) * (Math.PI * 2 * i / Math.max(1, cats.length)) - Math.PI / 2;
963
+ const at = (i, f) => [cx + Math.cos(angle(i)) * radius * f, cy + Math.sin(angle(i)) * radius * f];
964
+ const empty = data.length === 0 || series.length === 0;
965
+ const summary = props.description ?? (empty ? "" : `Radar chart of ${series.length} series across ${cats.length} measures, scale 0 to ${format.value(max)}.`);
966
+ const renderTable = () => {
967
+ const columns = [{
968
+ key: "category",
969
+ header: messages.categoryHeader,
970
+ rowHeader: true
971
+ }, ...series.map((s) => ({
972
+ key: s.key,
973
+ header: s.label,
974
+ align: "end",
975
+ cell: (r) => format.value(val(s, r.row))
976
+ }))];
977
+ return /* @__PURE__ */ jsx(Table, {
978
+ columns,
979
+ rows: data.map((row, i) => ({
980
+ category: cats[i] ?? "",
981
+ row
982
+ })),
983
+ getRowId: (r) => r.category,
984
+ caption: messages.tableCaption(title),
985
+ density: "compact"
986
+ });
987
+ };
988
+ return /* @__PURE__ */ jsx(ChartFrame, {
989
+ ...frameProps(props, "radar", messages, height),
990
+ description: summary,
991
+ table: empty ? "none" : table,
992
+ renderTable,
993
+ announcement: explorer.announcement,
994
+ legend: !empty && (props.legend ?? series.length > 1) ? /* @__PURE__ */ jsx(Legend, {
995
+ label: `${title}: legend`,
996
+ items: series.map((s, i) => ({
997
+ key: s.key,
998
+ label: s.label,
999
+ color: seriesColor(i, s.color)
1000
+ }))
1001
+ }) : void 0,
1002
+ children: /* @__PURE__ */ jsx("div", {
1003
+ ref: plotRef,
1004
+ className: charts_module_default.plotWrap,
1005
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
1006
+ height,
1007
+ children: emptyState ?? messages.empty
1008
+ }) : /* @__PURE__ */ jsxs(Plot, {
1009
+ title,
1010
+ height,
1011
+ width,
1012
+ explorer,
1013
+ hint,
1014
+ tooltip: explorer.active !== null ? {
1015
+ text: texts[explorer.active] ?? "",
1016
+ x: at(explorer.active, 1)[0],
1017
+ y: at(explorer.active, 1)[1]
1018
+ } : null,
1019
+ children: [
1020
+ [
1021
+ .25,
1022
+ .5,
1023
+ .75,
1024
+ 1
1025
+ ].map((f) => /* @__PURE__ */ jsx("polygon", {
1026
+ points: cats.map((_, i) => at(i, f).join(",")).join(" "),
1027
+ className: charts_module_default.gridLine,
1028
+ fill: "none"
1029
+ }, f)),
1030
+ cats.map((c, i) => {
1031
+ const [x, y] = at(i, 1);
1032
+ const [lx, ly] = at(i, 1.14);
1033
+ return /* @__PURE__ */ jsxs("g", {
1034
+ onPointerEnter: () => explorer.setActive(i),
1035
+ children: [/* @__PURE__ */ jsx("line", {
1036
+ x1: cx,
1037
+ y1: cy,
1038
+ x2: x,
1039
+ y2: y,
1040
+ className: charts_module_default.gridLine,
1041
+ "data-active": explorer.active === i || void 0
1042
+ }), /* @__PURE__ */ jsx("text", {
1043
+ x: lx,
1044
+ y: ly + 4,
1045
+ textAnchor: Math.abs(lx - cx) < 4 ? "middle" : lx > cx ? "start" : "end",
1046
+ className: charts_module_default.tickLabel,
1047
+ children: c
1048
+ })]
1049
+ }, c);
1050
+ }),
1051
+ series.map((s, k) => /* @__PURE__ */ jsx("polygon", {
1052
+ points: data.map((r, i) => at(i, val(s, r) / max).join(",")).join(" "),
1053
+ fill: `color-mix(in srgb, ${seriesColor(k, s.color)} 18%, transparent)`,
1054
+ stroke: seriesColor(k, s.color),
1055
+ strokeWidth: 2
1056
+ }, s.key))
1057
+ ]
1058
+ })
1059
+ })
1060
+ });
1061
+ }
1062
+ var total = (n) => n.children?.length ? n.children.reduce((s, c) => s + total(c), 0) : Math.max(0, n.value ?? 0);
1063
+ /** Squarified layout of weighted items in a rectangle (Bruls, Huizing, van Wijk). */
1064
+ function squarify(items, x, y, w, h) {
1065
+ const out = [];
1066
+ const sum = items.reduce((s, i) => s + i.weight, 0);
1067
+ if (!sum || w <= 0 || h <= 0) return out;
1068
+ const scale = w * h / sum;
1069
+ const rest = items.filter((i) => i.weight > 0).map((i) => ({
1070
+ item: i,
1071
+ area: i.weight * scale
1072
+ }));
1073
+ let box = {
1074
+ x,
1075
+ y,
1076
+ w,
1077
+ h
1078
+ };
1079
+ const worst = (row, side) => {
1080
+ const s = row.reduce((a, r) => a + r.area, 0);
1081
+ const mx = Math.max(...row.map((r) => r.area));
1082
+ const mn = Math.min(...row.map((r) => r.area));
1083
+ return Math.max(side * side * mx / (s * s), s * s / (side * side * mn));
1084
+ };
1085
+ while (rest.length) {
1086
+ const side = Math.min(box.w, box.h);
1087
+ const row = [rest.shift()];
1088
+ while (rest.length && worst([...row, rest[0]], side) <= worst(row, side)) row.push(rest.shift());
1089
+ const thick = row.reduce((a, r) => a + r.area, 0) / side;
1090
+ let offset = 0;
1091
+ for (const r of row) {
1092
+ const len = r.area / thick;
1093
+ out.push(box.w >= box.h ? {
1094
+ ...r.item,
1095
+ x: box.x,
1096
+ y: box.y + offset,
1097
+ w: thick,
1098
+ h: len
1099
+ } : {
1100
+ ...r.item,
1101
+ x: box.x + offset,
1102
+ y: box.y,
1103
+ w: len,
1104
+ h: thick
1105
+ });
1106
+ offset += len;
1107
+ }
1108
+ box = box.w >= box.h ? {
1109
+ x: box.x + thick,
1110
+ y: box.y,
1111
+ w: box.w - thick,
1112
+ h: box.h
1113
+ } : {
1114
+ x: box.x,
1115
+ y: box.y + thick,
1116
+ w: box.w,
1117
+ h: box.h - thick
1118
+ };
1119
+ }
1120
+ return out;
1121
+ }
1122
+ /** Parts of a whole by size, for many items or two levels (folders and files, regions and products). */
1123
+ function Treemap(props) {
1124
+ const { data, title, height = 300, table = "toggle", emptyState } = props;
1125
+ const { messages, format, plotRef, width, rtl, hint } = useChart(props);
1126
+ const sum = data.reduce((s, n) => s + total(n), 0);
1127
+ const groups = squarify(data.map((n, i) => ({
1128
+ node: n,
1129
+ group: i,
1130
+ weight: total(n)
1131
+ })), 0, 0, width, height);
1132
+ const tiles = groups.flatMap((g) => {
1133
+ const header = g.node.children?.length && g.h > 34 ? 18 : 0;
1134
+ return squarify(g.node.children?.length ? g.node.children.map((c) => ({
1135
+ node: c,
1136
+ weight: total(c)
1137
+ })) : [{
1138
+ node: g.node,
1139
+ weight: total(g.node)
1140
+ }], g.x, g.y + header, g.w, g.h - header).map((t) => ({
1141
+ path: g.node.children?.length ? `${g.node.label} › ${t.node.label}` : t.node.label,
1142
+ label: t.node.label,
1143
+ value: t.weight,
1144
+ group: g.group,
1145
+ x: rtl ? width - t.x - t.w : t.x,
1146
+ y: t.y,
1147
+ w: t.w,
1148
+ h: t.h
1149
+ }));
1150
+ });
1151
+ const texts = tiles.map((t) => `${t.path}: ${format.value(t.value)} (${format.percent(sum ? t.value / sum : 0)})`);
1152
+ const explorer = useExplorer(texts);
1153
+ const empty = sum === 0;
1154
+ const biggest = [...tiles].sort((a, b) => b.value - a.value).slice(0, 3);
1155
+ const summary = props.description ?? (empty ? "" : `Treemap of ${tiles.length} items, total ${format.value(sum)}. Largest: ${biggest.map((t) => `${t.path} (${format.percent(t.value / sum)})`).join("; ")}.`);
1156
+ const renderTable = () => {
1157
+ const columns = [
1158
+ {
1159
+ key: "path",
1160
+ header: messages.categoryHeader,
1161
+ rowHeader: true,
1162
+ sortable: true,
1163
+ sortValue: (t) => t.path
1164
+ },
1165
+ {
1166
+ key: "value",
1167
+ header: title,
1168
+ align: "end",
1169
+ sortable: true,
1170
+ sortValue: (t) => t.value,
1171
+ cell: (t) => format.value(t.value)
1172
+ },
1173
+ {
1174
+ key: "share",
1175
+ header: messages.shareHeader,
1176
+ align: "end",
1177
+ cell: (t) => format.percent(t.value / sum)
1178
+ }
1179
+ ];
1180
+ return /* @__PURE__ */ jsx(Table, {
1181
+ columns,
1182
+ rows: tiles.map((t, i) => ({
1183
+ ...t,
1184
+ i
1185
+ })),
1186
+ getRowId: (t) => String(t.i),
1187
+ caption: messages.tableCaption(title),
1188
+ density: "compact"
1189
+ });
1190
+ };
1191
+ return /* @__PURE__ */ jsx(ChartFrame, {
1192
+ ...frameProps(props, "treemap", messages, height),
1193
+ description: summary,
1194
+ table: empty ? "none" : table,
1195
+ renderTable,
1196
+ announcement: explorer.announcement,
1197
+ children: /* @__PURE__ */ jsx("div", {
1198
+ ref: plotRef,
1199
+ className: charts_module_default.plotWrap,
1200
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
1201
+ height,
1202
+ children: emptyState ?? messages.empty
1203
+ }) : /* @__PURE__ */ jsxs(Plot, {
1204
+ title,
1205
+ height,
1206
+ width,
1207
+ explorer,
1208
+ hint,
1209
+ tooltip: explorer.active !== null && tiles[explorer.active] ? {
1210
+ text: texts[explorer.active] ?? "",
1211
+ x: (tiles[explorer.active]?.x ?? 0) + 4,
1212
+ y: tiles[explorer.active]?.y ?? 0
1213
+ } : null,
1214
+ children: [groups.map((g) => g.node.children?.length && g.h > 34 ? /* @__PURE__ */ jsx("text", {
1215
+ x: rtl ? width - g.x - 6 : g.x + 6,
1216
+ y: g.y + 13,
1217
+ className: charts_module_default.treemapGroup,
1218
+ textAnchor: rtl ? "end" : "start",
1219
+ children: g.node.label
1220
+ }, `g${g.group}`) : null), tiles.map((t, i) => /* @__PURE__ */ jsxs("g", {
1221
+ onPointerEnter: () => explorer.setActive(i),
1222
+ children: [/* @__PURE__ */ jsx("rect", {
1223
+ x: t.x + 1,
1224
+ y: t.y + 1,
1225
+ width: Math.max(0, t.w - 2),
1226
+ height: Math.max(0, t.h - 2),
1227
+ rx: 3,
1228
+ fill: `color-mix(in srgb, ${seriesColor(t.group)} ${38 + i % 3 * 10}%, var(--pl-color-bg-surface))`,
1229
+ className: charts_module_default.cell,
1230
+ "data-active": explorer.active === i || void 0
1231
+ }), t.w > 48 && t.h > 22 ? /* @__PURE__ */ jsx("text", {
1232
+ x: rtl ? t.x + t.w - 6 : t.x + 6,
1233
+ y: t.y + 16,
1234
+ className: charts_module_default.cellText,
1235
+ textAnchor: rtl ? "end" : "start",
1236
+ children: t.label
1237
+ }) : null]
1238
+ }, i))]
1239
+ })
1240
+ })
1241
+ });
1242
+ }
1243
+ /** Flows between stages (budget → departments → costs, traffic sources → pages). Arrow keys move through the flows. */
1244
+ function Sankey(props) {
1245
+ const { nodes, links, title, height = 320, table = "toggle", emptyState } = props;
1246
+ const { messages, format, plotRef, width, rtl, hint } = useChart(props);
1247
+ const byId = new Map(nodes.map((n) => [n.id, n]));
1248
+ const valid = links.filter((l) => byId.has(l.source) && byId.has(l.target) && l.value > 0 && l.source !== l.target);
1249
+ const depth = new Map(nodes.map((n) => [n.id, 0]));
1250
+ for (let pass = 0; pass < nodes.length; pass++) for (const l of valid) depth.set(l.target, Math.max(depth.get(l.target) ?? 0, (depth.get(l.source) ?? 0) + 1));
1251
+ const columns = Math.max(1, ...[...depth.values()].map((d) => d + 1));
1252
+ const flow = (id) => Math.max(valid.filter((l) => l.source === id).reduce((s, l) => s + l.value, 0), valid.filter((l) => l.target === id).reduce((s, l) => s + l.value, 0));
1253
+ const nodeW = 12;
1254
+ const gap = 10;
1255
+ const colX = (d) => (columns === 1 ? 0 : d / (columns - 1) * (width - nodeW - 140)) + 70;
1256
+ const perColumn = Array.from({ length: columns }, (_, d) => nodes.filter((n) => depth.get(n.id) === d));
1257
+ const scale = Math.min(...perColumn.map((col) => (height - 8 - gap * Math.max(0, col.length - 1)) / Math.max(1, col.reduce((s, n) => s + flow(n.id), 0))));
1258
+ const box = /* @__PURE__ */ new Map();
1259
+ perColumn.forEach((col, d) => {
1260
+ let y = 4;
1261
+ for (const n of col) {
1262
+ const h = Math.max(2, flow(n.id) * scale);
1263
+ const x = rtl ? width - colX(d) - nodeW : colX(d);
1264
+ box.set(n.id, {
1265
+ x,
1266
+ y,
1267
+ h,
1268
+ outY: y,
1269
+ inY: y
1270
+ });
1271
+ y += h + gap;
1272
+ }
1273
+ });
1274
+ const bands = valid.map((l) => {
1275
+ const s = box.get(l.source);
1276
+ const t = box.get(l.target);
1277
+ const w = l.value * scale;
1278
+ if (!s || !t) return null;
1279
+ const y1 = s.outY + w / 2;
1280
+ const y2 = t.inY + w / 2;
1281
+ s.outY += w;
1282
+ t.inY += w;
1283
+ const x1 = rtl ? s.x : s.x + nodeW;
1284
+ const x2 = rtl ? t.x + nodeW : t.x;
1285
+ const mx = (x1 + x2) / 2;
1286
+ return {
1287
+ link: l,
1288
+ w,
1289
+ d: `M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`,
1290
+ mid: {
1291
+ x: mx,
1292
+ y: (y1 + y2) / 2
1293
+ }
1294
+ };
1295
+ });
1296
+ const totalIn = nodes.filter((n) => depth.get(n.id) === 0).reduce((s, n) => s + flow(n.id), 0);
1297
+ const texts = valid.map((l) => `${byId.get(l.source)?.label} to ${byId.get(l.target)?.label}: ${format.value(l.value)}${totalIn ? ` (${format.percent(l.value / totalIn)})` : ""}`);
1298
+ const explorer = useExplorer(texts);
1299
+ const empty = valid.length === 0;
1300
+ const summary = props.description ?? (empty ? "" : `Sankey diagram of ${valid.length} flows between ${nodes.length} nodes in ${columns} stages. Largest: ${[...valid].sort((a, b) => b.value - a.value).slice(0, 3).map((l) => `${byId.get(l.source)?.label} to ${byId.get(l.target)?.label} ${format.value(l.value)}`).join("; ")}.`);
1301
+ const renderTable = () => {
1302
+ return /* @__PURE__ */ jsx(Table, {
1303
+ columns: [
1304
+ {
1305
+ key: "source",
1306
+ header: "From",
1307
+ rowHeader: true,
1308
+ sortable: true,
1309
+ sortValue: (r) => r.source
1310
+ },
1311
+ {
1312
+ key: "target",
1313
+ header: "To",
1314
+ sortable: true,
1315
+ sortValue: (r) => r.target
1316
+ },
1317
+ {
1318
+ key: "value",
1319
+ header: title,
1320
+ align: "end",
1321
+ sortable: true,
1322
+ sortValue: (r) => r.value,
1323
+ cell: (r) => format.value(r.value)
1324
+ }
1325
+ ],
1326
+ rows: valid.map((l, i) => ({
1327
+ i,
1328
+ source: byId.get(l.source)?.label ?? "",
1329
+ target: byId.get(l.target)?.label ?? "",
1330
+ value: l.value
1331
+ })),
1332
+ getRowId: (r) => String(r.i),
1333
+ caption: messages.tableCaption(title),
1334
+ density: "compact"
1335
+ });
1336
+ };
1337
+ const activeBand = explorer.active === null ? null : bands[explorer.active];
1338
+ return /* @__PURE__ */ jsx(ChartFrame, {
1339
+ ...frameProps(props, "sankey", messages, height),
1340
+ description: summary,
1341
+ table: empty ? "none" : table,
1342
+ renderTable,
1343
+ announcement: explorer.announcement,
1344
+ children: /* @__PURE__ */ jsx("div", {
1345
+ ref: plotRef,
1346
+ className: charts_module_default.plotWrap,
1347
+ children: empty ? /* @__PURE__ */ jsx(Empty, {
1348
+ height,
1349
+ children: emptyState ?? messages.empty
1350
+ }) : /* @__PURE__ */ jsxs(Plot, {
1351
+ title,
1352
+ height,
1353
+ width,
1354
+ explorer,
1355
+ hint,
1356
+ tooltip: activeBand ? {
1357
+ text: texts[explorer.active ?? 0] ?? "",
1358
+ x: activeBand.mid.x,
1359
+ y: activeBand.mid.y
1360
+ } : null,
1361
+ children: [bands.map((b, i) => b ? /* @__PURE__ */ jsx("path", {
1362
+ d: b.d,
1363
+ strokeWidth: Math.max(1, b.w),
1364
+ stroke: seriesColor(nodes.findIndex((n) => n.id === b.link.source)),
1365
+ className: charts_module_default.sankeyLink,
1366
+ "data-active": explorer.active === i || void 0,
1367
+ onPointerEnter: () => explorer.setActive(i)
1368
+ }, i) : null), nodes.map((n) => {
1369
+ const b = box.get(n.id);
1370
+ if (!b) return null;
1371
+ const end = (depth.get(n.id) ?? 0) === columns - 1;
1372
+ const labelX = end !== rtl ? b.x - 6 : b.x + nodeW + 6;
1373
+ return /* @__PURE__ */ jsxs("g", { children: [/* @__PURE__ */ jsx("rect", {
1374
+ x: b.x,
1375
+ y: b.y,
1376
+ width: nodeW,
1377
+ height: b.h,
1378
+ rx: 2,
1379
+ className: charts_module_default.sankeyNode
1380
+ }), /* @__PURE__ */ jsx("text", {
1381
+ x: labelX,
1382
+ y: b.y + b.h / 2 + 4,
1383
+ textAnchor: end !== rtl ? "end" : "start",
1384
+ className: charts_module_default.tickLabel,
1385
+ children: n.label
1386
+ })] }, n.id);
1387
+ })]
1388
+ })
1389
+ })
1390
+ });
1391
+ }
1392
+ var STYLE_PROPS = [
1393
+ "fill",
1394
+ "stroke",
1395
+ "stroke-width",
1396
+ "stroke-dasharray",
1397
+ "opacity",
1398
+ "fill-opacity",
1399
+ "stroke-opacity",
1400
+ "font-family",
1401
+ "font-size",
1402
+ "font-weight",
1403
+ "text-anchor",
1404
+ "dominant-baseline"
1405
+ ];
1406
+ /**
1407
+ * The chart's drawing as a standalone SVG string: theme colours and fonts are resolved and
1408
+ * inlined, so the file looks the same outside the page. Pass the chart's `<figure>` (or any
1409
+ * element containing it).
1410
+ */
1411
+ function chartToSvg(root, { title } = {}) {
1412
+ const svg = root.querySelector("svg[data-chart-plot]");
1413
+ if (!svg) throw new Error("chartToSvg: no chart plot found");
1414
+ const clone = svg.cloneNode(true);
1415
+ const source = [svg, ...svg.querySelectorAll("*")];
1416
+ const target = [clone, ...clone.querySelectorAll("*")];
1417
+ source.forEach((el, i) => {
1418
+ const copy = target[i];
1419
+ if (!copy) return;
1420
+ const computed = getComputedStyle(el);
1421
+ copy.setAttribute("style", STYLE_PROPS.map((p) => `${p}:${computed.getPropertyValue(p)}`).join(";"));
1422
+ copy.removeAttribute("class");
1423
+ });
1424
+ const box = svg.getBoundingClientRect();
1425
+ clone.setAttribute("xmlns", "http://www.w3.org/2000/svg");
1426
+ clone.setAttribute("width", String(Math.round(box.width) || svg.viewBox.baseVal.width));
1427
+ clone.setAttribute("height", String(Math.round(box.height) || svg.viewBox.baseVal.height));
1428
+ clone.removeAttribute("aria-hidden");
1429
+ clone.setAttribute("role", "img");
1430
+ const name = title ?? root.querySelector("figcaption")?.textContent ?? "";
1431
+ if (name) {
1432
+ const t = document.createElementNS("http://www.w3.org/2000/svg", "title");
1433
+ t.textContent = name;
1434
+ clone.prepend(t);
1435
+ }
1436
+ return new XMLSerializer().serializeToString(clone);
1437
+ }
1438
+ /** Downloads the chart as an SVG or PNG file (PNG at `scale` × the on-screen size). */
1439
+ async function downloadChart(root, { format = "png", filename = "chart", scale = 2, background } = {}) {
1440
+ const svgText = chartToSvg(root);
1441
+ const save = (url, ext) => {
1442
+ const a = document.createElement("a");
1443
+ a.href = url;
1444
+ a.download = `${filename}.${ext}`;
1445
+ a.click();
1446
+ };
1447
+ const svgUrl = URL.createObjectURL(new Blob([svgText], { type: "image/svg+xml" }));
1448
+ if (format === "svg") {
1449
+ save(svgUrl, "svg");
1450
+ setTimeout(() => URL.revokeObjectURL(svgUrl), 1e3);
1451
+ return;
1452
+ }
1453
+ const image = new Image();
1454
+ await new Promise((resolve, reject) => {
1455
+ image.onload = () => resolve();
1456
+ image.onerror = () => reject(/* @__PURE__ */ new Error("downloadChart: the SVG could not be rendered"));
1457
+ image.src = svgUrl;
1458
+ });
1459
+ const canvas = document.createElement("canvas");
1460
+ canvas.width = Math.round(image.width * scale);
1461
+ canvas.height = Math.round(image.height * scale);
1462
+ const ctx = canvas.getContext("2d");
1463
+ if (!ctx) throw new Error("downloadChart: no canvas context");
1464
+ ctx.fillStyle = background ?? getComputedStyle(root).getPropertyValue("--pl-color-bg-surface").trim() ?? "#fff";
1465
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
1466
+ ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
1467
+ URL.revokeObjectURL(svgUrl);
1468
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
1469
+ if (!blob) throw new Error("downloadChart: PNG encoding failed");
1470
+ const pngUrl = URL.createObjectURL(blob);
1471
+ save(pngUrl, "png");
1472
+ setTimeout(() => URL.revokeObjectURL(pngUrl), 1e3);
1473
+ }
1474
+ export { BoxPlot, FunnelChart, Gauge, Heatmap, Histogram, RadarChart, Sankey, Treemap, WaterfallChart, boxStats, chartToSvg, downloadChart };
1475
+
1476
+ //# sourceMappingURL=item-charts.js.map