@tonycodes-ui/mortar 0.30.0 → 0.31.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.
@@ -0,0 +1,886 @@
1
+ import {
2
+ useId,
3
+ useLayoutEffect,
4
+ useRef,
5
+ useState,
6
+ type CSSProperties,
7
+ type KeyboardEvent,
8
+ type PointerEvent,
9
+ type ReactNode,
10
+ } from "react";
11
+ import { componentRoot, cx } from "./internal.js";
12
+ import { Button, EmptyState, Notice } from "./primitives.js";
13
+ import { Table } from "./application.js";
14
+ import {
15
+ bandPath,
16
+ extent,
17
+ linearScale,
18
+ linePath,
19
+ niceTicks,
20
+ seriesColour,
21
+ type ChartSlot,
22
+ type Point,
23
+ } from "./chart-core.js";
24
+
25
+ type Row = Record<string, unknown>;
26
+
27
+ export interface ChartSeries {
28
+ /** The row field this series plots. */
29
+ key: string;
30
+ label: string;
31
+ /** Pins the series colour so it never moves when other series change. Defaults to the series' position. */
32
+ slot?: ChartSlot;
33
+ /** Formats this series' values; defaults to the y axis format. */
34
+ format?: (value: number) => string;
35
+ }
36
+
37
+ export interface ChartX {
38
+ /** The row field for the x value or category. */
39
+ key: string;
40
+ label?: string;
41
+ format?: (value: unknown) => string;
42
+ }
43
+
44
+ export interface ChartY {
45
+ label?: string;
46
+ format?: (value: number) => string;
47
+ min?: number;
48
+ max?: number;
49
+ }
50
+
51
+ export interface ChartBaseProps {
52
+ /** The chart's accessible name, shown above it unless titleHidden. */
53
+ title: string;
54
+ titleHidden?: boolean;
55
+ /** A sentence that says what the chart shows; read before the chart. */
56
+ description?: string;
57
+ rows: Row[];
58
+ x: ChartX;
59
+ /** One to eight series; a ninth belongs in "Other" or another chart. */
60
+ series: ChartSeries[];
61
+ y?: ChartY;
62
+ /** Plot height in pixels; the width follows the container. Default 240. */
63
+ height?: number;
64
+ /** `auto` shows a legend for two or more series. */
65
+ legend?: "auto" | "hidden";
66
+ /** Offer a "Show data" table of the rows. Default true. */
67
+ tableView?: boolean;
68
+ loading?: boolean;
69
+ error?: string;
70
+ /** Shown when there are no rows. */
71
+ empty?: { title: string; description?: string };
72
+ id?: string;
73
+ className?: string;
74
+ }
75
+
76
+ const numberFormat = new Intl.NumberFormat(undefined, {
77
+ maximumFractionDigits: 2,
78
+ });
79
+ const defaultY = (n: number) => numberFormat.format(n);
80
+ const defaultX = (v: unknown) =>
81
+ v instanceof Date ? v.toLocaleDateString() : String(v ?? "");
82
+ /**
83
+ * A row's value for a series. Numbers pass through; numeric strings (common
84
+ * in JSON from APIs) are read as numbers; anything else is a missing value.
85
+ */
86
+ const valueOf = (row: Row, key: string) => {
87
+ const v = row[key];
88
+ if (typeof v === "number") return v;
89
+ if (typeof v === "string" && v.trim() !== "") {
90
+ const n = Number(v);
91
+ return Number.isFinite(n) ? n : Number.NaN;
92
+ }
93
+ return Number.NaN;
94
+ };
95
+
96
+ /** At most eight series: slots are never reused, so a ninth is not drawn. */
97
+ const limitSeries = (series: ChartSeries[]) => series.slice(0, 8);
98
+
99
+ /**
100
+ * One distinct slot per series. Pinned slots are kept (a repeated pin goes to
101
+ * the first free slot); unpinned series take the lowest slots nobody pinned.
102
+ */
103
+ export function assignSlots(series: ChartSeries[]): ChartSlot[] {
104
+ const taken = new Set<number>();
105
+ const slots: (ChartSlot | undefined)[] = series.map((s) => {
106
+ if (s.slot && !taken.has(s.slot)) {
107
+ taken.add(s.slot);
108
+ return s.slot;
109
+ }
110
+ return undefined;
111
+ });
112
+ let next = 1;
113
+ return slots.map((slot) => {
114
+ if (slot) return slot;
115
+ while (taken.has(next)) next++;
116
+ taken.add(next);
117
+ return next as ChartSlot;
118
+ });
119
+ }
120
+
121
+ const colour = (slot: ChartSlot) =>
122
+ ({ "--m-series": seriesColour(slot) }) as CSSProperties;
123
+
124
+ /**
125
+ * Diverging stack: per row, positive values stack up from zero and negative
126
+ * values stack down from zero, so layers never overlap. A missing value has
127
+ * no extent and leaves a gap. Returns [from, to] per series per row.
128
+ */
129
+ function stack(rows: Row[], series: ChartSeries[]) {
130
+ return rows.map((row) => {
131
+ let up = 0;
132
+ let down = 0;
133
+ return series.map((s) => {
134
+ const v = valueOf(row, s.key);
135
+ if (!Number.isFinite(v)) return [Number.NaN, Number.NaN] as const;
136
+ if (v >= 0) {
137
+ const from = up;
138
+ up += v;
139
+ return [from, up] as const;
140
+ }
141
+ const from = down;
142
+ down += v;
143
+ return [from, down] as const;
144
+ });
145
+ });
146
+ }
147
+
148
+ /** A bar with rounded corners on its data end only; the baseline end stays square. */
149
+ function barPath(
150
+ x: number,
151
+ y: number,
152
+ w: number,
153
+ h: number,
154
+ up: boolean,
155
+ r = 4,
156
+ ) {
157
+ const radius = Math.max(0, Math.min(r, w / 2, h));
158
+ if (!radius) return `M${x} ${y}h${w}v${h}h${-w}Z`;
159
+ return up
160
+ ? `M${x} ${y + h}V${y + radius}Q${x} ${y} ${x + radius} ${y}H${x + w - radius}Q${x + w} ${y} ${x + w} ${y + radius}V${y + h}Z`
161
+ : `M${x} ${y}V${y + h - radius}Q${x} ${y + h} ${x + radius} ${y + h}H${x + w - radius}Q${x + w} ${y + h} ${x + w} ${y + h - radius}V${y}Z`;
162
+ }
163
+
164
+ // Plot margins in pixels. The top grows to fit a y axis label; the left grows
165
+ // with the widest y tick label.
166
+ const TOP = 12;
167
+ const LABELLED_TOP = 28;
168
+ const BOTTOM = 28;
169
+ const CHAR = 7;
170
+ // Below this width, line charts drop direct end labels and keep the legend.
171
+ const DIRECT_MIN_WIDTH = 400;
172
+
173
+ interface Geometry {
174
+ width: number;
175
+ height: number;
176
+ left: number;
177
+ right: number;
178
+ top: number;
179
+ bottom: number;
180
+ ticks: number[];
181
+ y: (value: number) => number;
182
+ }
183
+
184
+ /** Container width, measured after layout; 640 until then (and on the server). */
185
+ function useWidth() {
186
+ const ref = useRef<HTMLDivElement>(null);
187
+ const [width, setWidth] = useState(640);
188
+ useLayoutEffect(() => {
189
+ const el = ref.current;
190
+ if (!el) return;
191
+ const measure = () => {
192
+ const next = Math.round(el.getBoundingClientRect().width);
193
+ if (next > 0) setWidth((old) => (old === next ? old : next));
194
+ };
195
+ measure();
196
+ const observer = new ResizeObserver(measure);
197
+ observer.observe(el);
198
+ return () => observer.disconnect();
199
+ }, []);
200
+ return [ref, width] as const;
201
+ }
202
+
203
+ /** A clip-path id that is safe inside url(#…), from React's useId. */
204
+ const useClipId = () => `m-chart-clip-${useId().replace(/[^\w-]/g, "")}`;
205
+
206
+ function geometry(
207
+ values: number[],
208
+ width: number,
209
+ height: number,
210
+ y: ChartY,
211
+ format: (n: number) => string,
212
+ rightPad: number,
213
+ zero: boolean,
214
+ ): Geometry {
215
+ let [min, max] = extent(values);
216
+ if (y.min !== undefined) min = y.min;
217
+ if (y.max !== undefined) max = y.max;
218
+ // Bars measure from zero, so the axis always includes it, whatever y says.
219
+ if (zero) {
220
+ min = Math.min(0, min);
221
+ max = Math.max(0, max);
222
+ }
223
+ if (!(min < max)) {
224
+ // An inverted or flat override: fall back to the data, then to a unit
225
+ // span, keeping zero where the chart measures from it.
226
+ [min, max] = extent(values);
227
+ if (zero) {
228
+ min = Math.min(0, min);
229
+ max = Math.max(0, max);
230
+ }
231
+ if (min === max) max = min + 1;
232
+ }
233
+ const ticks = niceTicks([min, max], Math.max(2, Math.floor(height / 48)));
234
+ const lo = Math.min(min, ticks[0]);
235
+ const hi = Math.max(max, ticks[ticks.length - 1]);
236
+ const left = Math.max(...ticks.map((t) => format(t).length)) * CHAR + 12;
237
+ const top = y.label ? LABELLED_TOP : TOP;
238
+ return {
239
+ width,
240
+ height,
241
+ left,
242
+ right: Math.max(left + 1, width - rightPad),
243
+ top,
244
+ bottom: height - BOTTOM,
245
+ ticks,
246
+ y: linearScale([lo, hi], [height - BOTTOM, top]),
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Spreads end-of-line labels so none overlap and all stay between the plot's
252
+ * top and bottom: pushed down from the top, then back up from the bottom.
253
+ */
254
+ export function spread(
255
+ positions: { y: number; key: string }[],
256
+ top: number,
257
+ bottom: number,
258
+ gap = 14,
259
+ ) {
260
+ const sorted = [...positions]
261
+ .map((p) => ({ ...p, y: Math.min(bottom, Math.max(top, p.y)) }))
262
+ .sort((a, b) => a.y - b.y);
263
+ for (let i = 1; i < sorted.length; i++)
264
+ sorted[i].y = Math.max(sorted[i].y, sorted[i - 1].y + gap);
265
+ for (let i = sorted.length - 1; i >= 0; i--) {
266
+ const limit = i === sorted.length - 1 ? bottom : sorted[i + 1].y - gap;
267
+ sorted[i].y = Math.max(top, Math.min(sorted[i].y, limit));
268
+ }
269
+ return new Map(sorted.map((p) => [p.key, p.y]));
270
+ }
271
+
272
+ /** x positions spread across the plot; a single row sits in the middle. */
273
+ const spreadX = (count: number, g: Geometry) =>
274
+ count === 1
275
+ ? [(g.left + g.right) / 2]
276
+ : Array.from({ length: count }, (_, i) =>
277
+ linearScale([0, count - 1], [g.left, g.right])(i),
278
+ );
279
+
280
+ /** A point with no known neighbour, which a line alone cannot show. */
281
+ const isolated = (points: Point[], j: number) =>
282
+ Number.isFinite(points[j].y) &&
283
+ !Number.isFinite(points[j - 1]?.y ?? Number.NaN) &&
284
+ !Number.isFinite(points[j + 1]?.y ?? Number.NaN);
285
+
286
+ interface FrameProps extends ChartBaseProps {
287
+ name: string;
288
+ slots: ChartSlot[];
289
+ /** Draws the plot for the measured geometry, highlighting the active index. */
290
+ plot: (width: number, active: number | null) => ReactNode;
291
+ /** x position of each row, for pointer hit-testing and the tooltip. */
292
+ positions: (width: number) => number[];
293
+ }
294
+
295
+ /**
296
+ * The chart frame: a named figure with its description, legend, plot,
297
+ * tooltip, keyboard navigation and a table view of the same rows.
298
+ */
299
+ function ChartFrame({
300
+ name,
301
+ title,
302
+ titleHidden = false,
303
+ description,
304
+ rows,
305
+ x,
306
+ series,
307
+ slots,
308
+ y = {},
309
+ legend = "auto",
310
+ tableView = true,
311
+ loading,
312
+ error,
313
+ empty = { title: "No data", description: "There is nothing to show yet." },
314
+ height = 240,
315
+ id,
316
+ className,
317
+ plot,
318
+ positions,
319
+ }: FrameProps) {
320
+ const autoId = useId();
321
+ const titleId = `${autoId}-title`;
322
+ const descId = `${autoId}-desc`;
323
+ const [ref, width] = useWidth();
324
+ const [activeState, setActive] = useState<number | null>(null);
325
+ // Only keyboard moves are announced: announcing every pointer move would
326
+ // flood a screen reader while the pointer crosses the chart.
327
+ const [announce, setAnnounce] = useState(false);
328
+ const [showTable, setShowTable] = useState(false);
329
+ // Rows can shrink while a point is active; never point past the end.
330
+ const active =
331
+ activeState !== null && activeState < rows.length ? activeState : null;
332
+ const xFormat = x.format ?? defaultX;
333
+ const valueFormat = (s: ChartSeries) => s.format ?? y.format ?? defaultY;
334
+ const xs = positions(width);
335
+
336
+ const describe = (index: number) =>
337
+ `${xFormat(rows[index][x.key])}: ${series
338
+ .map((s) => {
339
+ const v = valueOf(rows[index], s.key);
340
+ return `${s.label} ${Number.isFinite(v) ? valueFormat(s)(v) : "no value"}`;
341
+ })
342
+ .join(", ")}`;
343
+
344
+ const nearest = (px: number) => {
345
+ let best = 0;
346
+ for (let i = 1; i < xs.length; i++)
347
+ if (Math.abs(xs[i] - px) < Math.abs(xs[best] - px)) best = i;
348
+ return best;
349
+ };
350
+ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
351
+ const box = event.currentTarget.getBoundingClientRect();
352
+ if (!xs.length) return;
353
+ setAnnounce(false);
354
+ setActive(nearest(event.clientX - box.left));
355
+ };
356
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
357
+ const last = rows.length - 1;
358
+ const moves: Record<string, number> = {
359
+ ArrowRight: Math.min(last, (active ?? -1) + 1),
360
+ ArrowLeft: Math.max(0, (active ?? 1) - 1),
361
+ Home: 0,
362
+ End: last,
363
+ };
364
+ if (event.key in moves && last >= 0) {
365
+ event.preventDefault();
366
+ setAnnounce(true);
367
+ setActive(moves[event.key]);
368
+ } else if (event.key === "Escape") setActive(null);
369
+ };
370
+
371
+ const body = loading ? (
372
+ <p className="m-chart-state" role="status">
373
+ Loading chart…
374
+ </p>
375
+ ) : error ? (
376
+ <Notice title="Unable to load chart" tone="danger" announce>
377
+ {error}
378
+ </Notice>
379
+ ) : !rows.length ? (
380
+ <EmptyState title={empty.title} description={empty.description} />
381
+ ) : showTable ? (
382
+ <Table
383
+ caption={title}
384
+ rowHeaders
385
+ columns={[
386
+ // Every column needs a name, even when x has no label.
387
+ { key: "__x", label: x.label ?? x.key },
388
+ ...series.map((s) => ({
389
+ key: s.key,
390
+ label: s.label,
391
+ align: "end" as const,
392
+ })),
393
+ ]}
394
+ rows={rows.map((row) => ({
395
+ __x: xFormat(row[x.key]),
396
+ ...Object.fromEntries(
397
+ series.map((s) => {
398
+ const v = valueOf(row, s.key);
399
+ return [s.key, Number.isFinite(v) ? valueFormat(s)(v) : "—"];
400
+ }),
401
+ ),
402
+ }))}
403
+ />
404
+ ) : (
405
+ <div
406
+ className="m-chart-plot"
407
+ tabIndex={0}
408
+ role="group"
409
+ aria-labelledby={titleId}
410
+ aria-describedby={description ? descId : undefined}
411
+ aria-roledescription="chart"
412
+ onPointerMove={onPointerMove}
413
+ onPointerLeave={() => setActive(null)}
414
+ onKeyDown={onKeyDown}
415
+ onBlur={() => setActive(null)}
416
+ >
417
+ <svg width={width} height="100%" aria-hidden="true" focusable="false">
418
+ {plot(width, active)}
419
+ </svg>
420
+ {active !== null && (
421
+ <div
422
+ className="m-chart-tooltip"
423
+ style={{ left: xs[active] }}
424
+ data-side={xs[active] > width / 2 ? "start" : "end"}
425
+ aria-hidden="true"
426
+ >
427
+ <strong>{xFormat(rows[active][x.key])}</strong>
428
+ {series.map((s, i) => {
429
+ const v = valueOf(rows[active], s.key);
430
+ return (
431
+ <span key={s.key}>
432
+ <i style={colour(slots[i])} />
433
+ {s.label}
434
+ <b>{Number.isFinite(v) ? valueFormat(s)(v) : "—"}</b>
435
+ </span>
436
+ );
437
+ })}
438
+ </div>
439
+ )}
440
+ </div>
441
+ );
442
+
443
+ return (
444
+ <figure
445
+ id={id}
446
+ {...componentRoot(name)}
447
+ className={cx("m-chart", className)}
448
+ aria-labelledby={titleId}
449
+ >
450
+ <figcaption className="m-chart-head">
451
+ <span
452
+ id={titleId}
453
+ className={titleHidden ? "m-sr-only" : "m-chart-title"}
454
+ >
455
+ {title}
456
+ </span>
457
+ {description && (
458
+ <span id={descId} className="m-chart-description">
459
+ {description}
460
+ </span>
461
+ )}
462
+ </figcaption>
463
+ {legend === "auto" && series.length > 1 && !showTable && (
464
+ <ul className="m-chart-legend" aria-label="Legend">
465
+ {series.map((s, i) => (
466
+ <li key={s.key} style={colour(slots[i])}>
467
+ {s.label}
468
+ </li>
469
+ ))}
470
+ </ul>
471
+ )}
472
+ <div
473
+ ref={ref}
474
+ className="m-chart-body"
475
+ style={showTable ? undefined : { height }}
476
+ >
477
+ {body}
478
+ </div>
479
+ <p className="m-sr-only" aria-live="polite">
480
+ {announce && active !== null ? describe(active) : ""}
481
+ </p>
482
+ {tableView && rows.length > 0 && !loading && !error && (
483
+ <div className="m-chart-actions">
484
+ <Button variant="ghost" onClick={() => setShowTable((v) => !v)}>
485
+ {showTable ? "Show chart" : "Show data"}
486
+ </Button>
487
+ </div>
488
+ )}
489
+ </figure>
490
+ );
491
+ }
492
+
493
+ /** Gridlines, y labels and the y axis label for a geometry. */
494
+ function YAxis({
495
+ g,
496
+ format,
497
+ label,
498
+ }: {
499
+ g: Geometry;
500
+ format: (n: number) => string;
501
+ label?: string;
502
+ }) {
503
+ return (
504
+ <g className="m-chart-axis" aria-hidden="true">
505
+ {label && (
506
+ <text className="m-chart-axis-label" x={0} y={12}>
507
+ {label}
508
+ </text>
509
+ )}
510
+ {g.ticks.map((t) => (
511
+ <g key={t}>
512
+ <line x1={g.left} x2={g.right} y1={g.y(t)} y2={g.y(t)} />
513
+ <text x={g.left - 8} y={g.y(t)} dy="0.32em" textAnchor="end">
514
+ {format(t)}
515
+ </text>
516
+ </g>
517
+ ))}
518
+ </g>
519
+ );
520
+ }
521
+
522
+ /** Category labels along the bottom, thinned so they never overlap. */
523
+ function XLabels({
524
+ xs,
525
+ labels,
526
+ g,
527
+ }: {
528
+ xs: number[];
529
+ labels: string[];
530
+ g: Geometry;
531
+ }) {
532
+ const longest = Math.max(1, ...labels.map((l) => l.length)) * CHAR + 12;
533
+ const step = Math.max(
534
+ 1,
535
+ Math.ceil(
536
+ longest / Math.max(1, (g.right - g.left) / Math.max(1, xs.length)),
537
+ ),
538
+ );
539
+ return (
540
+ <g className="m-chart-axis" aria-hidden="true">
541
+ {xs.map((x, i) =>
542
+ i % step === 0 ? (
543
+ <text key={i} x={x} y={g.height - 8} textAnchor="middle">
544
+ {labels[i]}
545
+ </text>
546
+ ) : null,
547
+ )}
548
+ </g>
549
+ );
550
+ }
551
+
552
+ /** Clips marks to the plot, so a y min or max inside the data never spills. */
553
+ function PlotClip({ id, g }: { id: string; g: Geometry }) {
554
+ return (
555
+ <clipPath id={id}>
556
+ {/* A little slack keeps 2px lines and 4px markers at the edges whole. */}
557
+ <rect
558
+ x={g.left - 6}
559
+ y={g.top - 6}
560
+ width={g.right - g.left + 12}
561
+ height={g.bottom - g.top + 12}
562
+ />
563
+ </clipPath>
564
+ );
565
+ }
566
+
567
+ export interface LineChartProps extends ChartBaseProps {
568
+ /** Mark each value with a dot. */
569
+ markers?: boolean;
570
+ }
571
+
572
+ /** Change over time for one to eight series, with direct end labels for up to four. */
573
+ export function LineChart(input: LineChartProps) {
574
+ const props = { ...input, series: limitSeries(input.series) };
575
+ const { rows, x, series, y = {}, height = 240, markers = false } = props;
576
+ const format = y.format ?? defaultY;
577
+ const slots = assignSlots(series);
578
+ const clipId = useClipId();
579
+ const values = rows.flatMap((row) => series.map((s) => valueOf(row, s.key)));
580
+ const layout = (width: number) => {
581
+ const direct =
582
+ series.length > 1 && series.length <= 4 && width >= DIRECT_MIN_WIDTH;
583
+ const labelWidth = direct
584
+ ? Math.min(
585
+ width * 0.3,
586
+ Math.max(...series.map((s) => s.label.length)) * CHAR + 16,
587
+ )
588
+ : 12;
589
+ const g = geometry(values, width, height, y, format, labelWidth, false);
590
+ return { g, direct, xs: spreadX(rows.length, g) };
591
+ };
592
+ return (
593
+ <ChartFrame
594
+ {...props}
595
+ slots={slots}
596
+ name="LineChart"
597
+ className={cx("m-line-chart", props.className)}
598
+ positions={(width) => layout(width).xs}
599
+ plot={(width, active) => {
600
+ const { g, direct, xs } = layout(width);
601
+ const lines = series.map((s, i) => ({
602
+ s,
603
+ slot: slots[i],
604
+ points: rows.map<Point>((row, j) => ({
605
+ x: xs[j],
606
+ y: g.y(valueOf(row, s.key)),
607
+ })),
608
+ }));
609
+ const ends = spread(
610
+ lines.flatMap(({ s, points }) => {
611
+ const last = [...points]
612
+ .reverse()
613
+ .find((p) => Number.isFinite(p.y));
614
+ // A line whose end is clipped out of the plot gets no label.
615
+ return last && last.y >= g.top && last.y <= g.bottom
616
+ ? [{ key: s.key, y: last.y }]
617
+ : [];
618
+ }),
619
+ g.top,
620
+ g.bottom,
621
+ );
622
+ return (
623
+ <g>
624
+ <PlotClip id={clipId} g={g} />
625
+ <YAxis g={g} format={format} label={y.label} />
626
+ <XLabels
627
+ xs={xs}
628
+ labels={rows.map((r) => (x.format ?? defaultX)(r[x.key]))}
629
+ g={g}
630
+ />
631
+ {active !== null && (
632
+ <line
633
+ className="m-chart-crosshair"
634
+ x1={xs[active]}
635
+ x2={xs[active]}
636
+ y1={g.top}
637
+ y2={g.bottom}
638
+ />
639
+ )}
640
+ {lines.map(({ s, slot, points }) => (
641
+ <g key={s.key} style={colour(slot)}>
642
+ <g clipPath={`url(#${clipId})`}>
643
+ <path className="m-chart-line" d={linePath(points)} />
644
+ {points.map((p, j) =>
645
+ Number.isFinite(p.y) &&
646
+ (markers || j === active || isolated(points, j)) ? (
647
+ <circle
648
+ key={j}
649
+ className="m-chart-marker"
650
+ cx={p.x}
651
+ cy={p.y}
652
+ r="4"
653
+ />
654
+ ) : null,
655
+ )}
656
+ </g>
657
+ {direct && ends.has(s.key) && (
658
+ <text
659
+ className="m-chart-end-label"
660
+ x={g.right + 8}
661
+ y={ends.get(s.key)}
662
+ dy="0.32em"
663
+ >
664
+ {s.label}
665
+ </text>
666
+ )}
667
+ </g>
668
+ ))}
669
+ </g>
670
+ );
671
+ }}
672
+ />
673
+ );
674
+ }
675
+
676
+ export interface AreaChartProps extends ChartBaseProps {
677
+ /**
678
+ * Stack the series so the top edge is their total. Default true. Without
679
+ * stacking, several series draw as lines only: overlapping fills hide each
680
+ * other.
681
+ */
682
+ stacked?: boolean;
683
+ }
684
+
685
+ /** Change over time where volume matters; stacked when the series sum to a whole. */
686
+ export function AreaChart(input: AreaChartProps) {
687
+ const props = { ...input, series: limitSeries(input.series) };
688
+ const { rows, series, y = {}, height = 240, stacked = true } = props;
689
+ const format = y.format ?? defaultY;
690
+ const slots = assignSlots(series);
691
+ const clipId = useClipId();
692
+ const fill = stacked || series.length === 1;
693
+ // [from, to] per row and series: a diverging stack, or zero to the value.
694
+ const layers = stacked
695
+ ? stack(rows, series)
696
+ : rows.map((row) => series.map((s) => [0, valueOf(row, s.key)] as const));
697
+ const values = layers.flat(2).concat(0);
698
+ const layout = (width: number) => {
699
+ const g = geometry(values, width, height, y, format, 12, true);
700
+ return { g, xs: spreadX(rows.length, g) };
701
+ };
702
+ return (
703
+ <ChartFrame
704
+ {...props}
705
+ slots={slots}
706
+ name="AreaChart"
707
+ className={cx("m-area-chart", props.className)}
708
+ positions={(width) => layout(width).xs}
709
+ plot={(width, active) => {
710
+ const { g, xs } = layout(width);
711
+ return (
712
+ <g>
713
+ <PlotClip id={clipId} g={g} />
714
+ <YAxis g={g} format={format} label={y.label} />
715
+ <XLabels
716
+ xs={xs}
717
+ labels={rows.map((r) =>
718
+ (props.x.format ?? defaultX)(r[props.x.key]),
719
+ )}
720
+ g={g}
721
+ />
722
+ {/* Each layer fills only its own band, from where it starts to
723
+ where it ends, so fills never overlap and gaps stay gaps. */}
724
+ <g clipPath={`url(#${clipId})`}>
725
+ {series.map((s, i) => {
726
+ const end = rows.map<Point>((_, j) => ({
727
+ x: xs[j],
728
+ y: g.y(layers[j][i][1]),
729
+ }));
730
+ const start = rows.map<Point>((_, j) => ({
731
+ x: xs[j],
732
+ y: Number.isFinite(layers[j][i][1])
733
+ ? g.y(layers[j][i][0])
734
+ : Number.NaN,
735
+ }));
736
+ return (
737
+ <g key={s.key} style={colour(slots[i])}>
738
+ {fill && (
739
+ <path className="m-chart-area" d={bandPath(end, start)} />
740
+ )}
741
+ <path className="m-chart-line" d={linePath(end)} />
742
+ {end.map((p, j) =>
743
+ Number.isFinite(p.y) &&
744
+ (j === active || isolated(end, j)) ? (
745
+ <circle
746
+ key={j}
747
+ className="m-chart-marker"
748
+ cx={p.x}
749
+ cy={p.y}
750
+ r="4"
751
+ />
752
+ ) : null,
753
+ )}
754
+ </g>
755
+ );
756
+ })}
757
+ </g>
758
+ {active !== null && (
759
+ <line
760
+ className="m-chart-crosshair"
761
+ x1={xs[active]}
762
+ x2={xs[active]}
763
+ y1={g.top}
764
+ y2={g.bottom}
765
+ />
766
+ )}
767
+ </g>
768
+ );
769
+ }}
770
+ />
771
+ );
772
+ }
773
+
774
+ export interface BarChartProps extends ChartBaseProps {
775
+ /** `grouped` puts series side by side; `stacked` stacks them when they sum to a whole. */
776
+ layout?: "grouped" | "stacked";
777
+ }
778
+
779
+ /** Compares values across categories. Bars always start at zero. */
780
+ export function BarChart(input: BarChartProps) {
781
+ const props = { ...input, series: limitSeries(input.series) };
782
+ const { rows, series, y = {}, height = 240, layout = "grouped" } = props;
783
+ const format = y.format ?? defaultY;
784
+ const slots = assignSlots(series);
785
+ const clipId = useClipId();
786
+ const stacked = layout === "stacked" && series.length > 1;
787
+ // [from, to] per row and series: a diverging stack, or zero to the value.
788
+ const layers = stacked
789
+ ? stack(rows, series)
790
+ : rows.map((row) => series.map((s) => [0, valueOf(row, s.key)] as const));
791
+ const values = layers.flat(2).concat(0);
792
+ // The outermost segment on each side of zero carries the rounded data end.
793
+ const ends = layers.map((row) => {
794
+ let up = -1;
795
+ let down = -1;
796
+ row.forEach(([from, to], i) => {
797
+ if (to > from) up = i;
798
+ else if (to < from) down = i;
799
+ });
800
+ return { up, down };
801
+ });
802
+ const band = (width: number) => {
803
+ const g = geometry(values, width, height, y, format, 12, true);
804
+ const step = (g.right - g.left) / Math.max(1, rows.length);
805
+ const xs = rows.map((_, i) => g.left + step * (i + 0.5));
806
+ return { g, step, xs, bar: Math.min(48, step * 0.7) };
807
+ };
808
+ return (
809
+ <ChartFrame
810
+ {...props}
811
+ slots={slots}
812
+ name="BarChart"
813
+ className={cx("m-bar-chart", props.className)}
814
+ positions={(width) => band(width).xs}
815
+ plot={(width, active) => {
816
+ const { g, step, xs, bar } = band(width);
817
+ const zero = g.y(0);
818
+ const groupWidth = stacked ? bar : bar / series.length;
819
+ return (
820
+ <g>
821
+ <PlotClip id={clipId} g={g} />
822
+ <YAxis g={g} format={format} label={y.label} />
823
+ <XLabels
824
+ xs={xs}
825
+ labels={rows.map((r) =>
826
+ (props.x.format ?? defaultX)(r[props.x.key]),
827
+ )}
828
+ g={g}
829
+ />
830
+ <g clipPath={`url(#${clipId})`}>
831
+ {layers.map((row, j) => (
832
+ <g key={j} data-active={active === j || undefined}>
833
+ {active === j && (
834
+ <rect
835
+ className="m-chart-band"
836
+ x={xs[j] - step / 2}
837
+ width={step}
838
+ y={g.top}
839
+ height={g.bottom - g.top}
840
+ />
841
+ )}
842
+ {row.map(([from, to], i) => {
843
+ if (!Number.isFinite(to) || to === from) return null;
844
+ const left = stacked
845
+ ? xs[j] - bar / 2
846
+ : xs[j] - bar / 2 + i * groupWidth;
847
+ const top = Math.min(g.y(from), g.y(to));
848
+ const h = Math.abs(g.y(to) - g.y(from));
849
+ const w = Math.max(1, groupWidth - (stacked ? 0 : 2));
850
+ const up = to > from;
851
+ // Every grouped bar is its own data end; in a stack only
852
+ // the outermost segment on each side of zero is.
853
+ const isEnd =
854
+ !stacked || (up ? ends[j].up === i : ends[j].down === i);
855
+ return (
856
+ <path
857
+ key={series[i].key}
858
+ className="m-chart-bar"
859
+ style={colour(slots[i])}
860
+ d={barPath(
861
+ left + (stacked ? 0 : 1),
862
+ top,
863
+ w,
864
+ h,
865
+ up,
866
+ isEnd ? 4 : 0,
867
+ )}
868
+ />
869
+ );
870
+ })}
871
+ </g>
872
+ ))}
873
+ </g>
874
+ <line
875
+ className="m-chart-zero"
876
+ x1={g.left}
877
+ x2={g.right}
878
+ y1={zero}
879
+ y2={zero}
880
+ />
881
+ </g>
882
+ );
883
+ }}
884
+ />
885
+ );
886
+ }