@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.
- package/CHANGELOG.md +4 -4
- package/catalog.json +757 -361
- package/dist/agent-data.json +1 -1
- package/dist/chart-core.d.ts +2 -0
- package/dist/chart-core.js +27 -0
- package/dist/charts.d.ts +2 -0
- package/dist/charts.js +1 -0
- package/dist/xy-chart.d.ts +86 -0
- package/dist/xy-chart.js +391 -0
- package/docs/charts.md +44 -1
- package/package.json +1 -1
- package/src/chart-core.ts +29 -0
- package/src/charts.css +181 -0
- package/src/charts.ts +10 -0
- package/src/xy-chart.tsx +886 -0
package/dist/chart-core.d.ts
CHANGED
|
@@ -23,6 +23,8 @@ export declare function linePath(points: readonly Point[]): string;
|
|
|
23
23
|
* shape per run of finite values, so a missing value leaves a gap.
|
|
24
24
|
*/
|
|
25
25
|
export declare function areaPath(points: readonly Point[], baseline: number): string;
|
|
26
|
+
/** SVG path data for the band between an upper and a lower edge (a stacked layer). */
|
|
27
|
+
export declare function bandPath(upper: readonly Point[], lower: readonly Point[]): string;
|
|
26
28
|
/** A categorical series slot. There are eight and they are never reused: a
|
|
27
29
|
ninth series belongs in "Other" or in its own chart. */
|
|
28
30
|
export type ChartSlot = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
package/dist/chart-core.js
CHANGED
|
@@ -95,6 +95,33 @@ export function areaPath(points, baseline) {
|
|
|
95
95
|
close();
|
|
96
96
|
return d;
|
|
97
97
|
}
|
|
98
|
+
/** SVG path data for the band between an upper and a lower edge (a stacked layer). */
|
|
99
|
+
export function bandPath(upper, lower) {
|
|
100
|
+
// One closed shape per run where both edges are known, so a missing value
|
|
101
|
+
// leaves a gap instead of a fill bridging it.
|
|
102
|
+
let d = "";
|
|
103
|
+
let run = [];
|
|
104
|
+
const close = () => {
|
|
105
|
+
if (run.length >= 2) {
|
|
106
|
+
const back = run
|
|
107
|
+
.map(([, l]) => l)
|
|
108
|
+
.reverse()
|
|
109
|
+
.map((p) => `L${round(p.x)} ${round(p.y)}`)
|
|
110
|
+
.join("");
|
|
111
|
+
d += `${linePath(run.map(([u]) => u))}${back}Z`;
|
|
112
|
+
}
|
|
113
|
+
run = [];
|
|
114
|
+
};
|
|
115
|
+
upper.forEach((u, i) => {
|
|
116
|
+
const l = lower[i];
|
|
117
|
+
if (Number.isFinite(u.y) && l && Number.isFinite(l.y))
|
|
118
|
+
run.push([u, l]);
|
|
119
|
+
else
|
|
120
|
+
close();
|
|
121
|
+
});
|
|
122
|
+
close();
|
|
123
|
+
return d;
|
|
124
|
+
}
|
|
98
125
|
const round = (n) => Math.round(n * 100) / 100;
|
|
99
126
|
/** The CSS colour of a series slot, from the --m-chart-* tokens. */
|
|
100
127
|
export const seriesColour = (slot) => `var(--m-chart-${slot})`;
|
package/dist/charts.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { Sparkline } from "./sparkline.js";
|
|
2
|
+
export { LineChart, AreaChart, BarChart } from "./xy-chart.js";
|
|
2
3
|
export type { SparklineProps } from "./sparkline.js";
|
|
4
|
+
export type { ChartBaseProps, ChartSeries, ChartX, ChartY, LineChartProps, AreaChartProps, BarChartProps, } from "./xy-chart.js";
|
|
3
5
|
export type { ChartSlot } from "./chart-core.js";
|
package/dist/charts.js
CHANGED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type ChartSlot } from "./chart-core.js";
|
|
2
|
+
type Row = Record<string, unknown>;
|
|
3
|
+
export interface ChartSeries {
|
|
4
|
+
/** The row field this series plots. */
|
|
5
|
+
key: string;
|
|
6
|
+
label: string;
|
|
7
|
+
/** Pins the series colour so it never moves when other series change. Defaults to the series' position. */
|
|
8
|
+
slot?: ChartSlot;
|
|
9
|
+
/** Formats this series' values; defaults to the y axis format. */
|
|
10
|
+
format?: (value: number) => string;
|
|
11
|
+
}
|
|
12
|
+
export interface ChartX {
|
|
13
|
+
/** The row field for the x value or category. */
|
|
14
|
+
key: string;
|
|
15
|
+
label?: string;
|
|
16
|
+
format?: (value: unknown) => string;
|
|
17
|
+
}
|
|
18
|
+
export interface ChartY {
|
|
19
|
+
label?: string;
|
|
20
|
+
format?: (value: number) => string;
|
|
21
|
+
min?: number;
|
|
22
|
+
max?: number;
|
|
23
|
+
}
|
|
24
|
+
export interface ChartBaseProps {
|
|
25
|
+
/** The chart's accessible name, shown above it unless titleHidden. */
|
|
26
|
+
title: string;
|
|
27
|
+
titleHidden?: boolean;
|
|
28
|
+
/** A sentence that says what the chart shows; read before the chart. */
|
|
29
|
+
description?: string;
|
|
30
|
+
rows: Row[];
|
|
31
|
+
x: ChartX;
|
|
32
|
+
/** One to eight series; a ninth belongs in "Other" or another chart. */
|
|
33
|
+
series: ChartSeries[];
|
|
34
|
+
y?: ChartY;
|
|
35
|
+
/** Plot height in pixels; the width follows the container. Default 240. */
|
|
36
|
+
height?: number;
|
|
37
|
+
/** `auto` shows a legend for two or more series. */
|
|
38
|
+
legend?: "auto" | "hidden";
|
|
39
|
+
/** Offer a "Show data" table of the rows. Default true. */
|
|
40
|
+
tableView?: boolean;
|
|
41
|
+
loading?: boolean;
|
|
42
|
+
error?: string;
|
|
43
|
+
/** Shown when there are no rows. */
|
|
44
|
+
empty?: {
|
|
45
|
+
title: string;
|
|
46
|
+
description?: string;
|
|
47
|
+
};
|
|
48
|
+
id?: string;
|
|
49
|
+
className?: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* One distinct slot per series. Pinned slots are kept (a repeated pin goes to
|
|
53
|
+
* the first free slot); unpinned series take the lowest slots nobody pinned.
|
|
54
|
+
*/
|
|
55
|
+
export declare function assignSlots(series: ChartSeries[]): ChartSlot[];
|
|
56
|
+
/**
|
|
57
|
+
* Spreads end-of-line labels so none overlap and all stay between the plot's
|
|
58
|
+
* top and bottom: pushed down from the top, then back up from the bottom.
|
|
59
|
+
*/
|
|
60
|
+
export declare function spread(positions: {
|
|
61
|
+
y: number;
|
|
62
|
+
key: string;
|
|
63
|
+
}[], top: number, bottom: number, gap?: number): Map<string, number>;
|
|
64
|
+
export interface LineChartProps extends ChartBaseProps {
|
|
65
|
+
/** Mark each value with a dot. */
|
|
66
|
+
markers?: boolean;
|
|
67
|
+
}
|
|
68
|
+
/** Change over time for one to eight series, with direct end labels for up to four. */
|
|
69
|
+
export declare function LineChart(input: LineChartProps): import("react").JSX.Element;
|
|
70
|
+
export interface AreaChartProps extends ChartBaseProps {
|
|
71
|
+
/**
|
|
72
|
+
* Stack the series so the top edge is their total. Default true. Without
|
|
73
|
+
* stacking, several series draw as lines only: overlapping fills hide each
|
|
74
|
+
* other.
|
|
75
|
+
*/
|
|
76
|
+
stacked?: boolean;
|
|
77
|
+
}
|
|
78
|
+
/** Change over time where volume matters; stacked when the series sum to a whole. */
|
|
79
|
+
export declare function AreaChart(input: AreaChartProps): import("react").JSX.Element;
|
|
80
|
+
export interface BarChartProps extends ChartBaseProps {
|
|
81
|
+
/** `grouped` puts series side by side; `stacked` stacks them when they sum to a whole. */
|
|
82
|
+
layout?: "grouped" | "stacked";
|
|
83
|
+
}
|
|
84
|
+
/** Compares values across categories. Bars always start at zero. */
|
|
85
|
+
export declare function BarChart(input: BarChartProps): import("react").JSX.Element;
|
|
86
|
+
export {};
|
package/dist/xy-chart.js
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useId, useLayoutEffect, useRef, useState, } from "react";
|
|
3
|
+
import { componentRoot, cx } from "./internal.js";
|
|
4
|
+
import { Button, EmptyState, Notice } from "./primitives.js";
|
|
5
|
+
import { Table } from "./application.js";
|
|
6
|
+
import { bandPath, extent, linearScale, linePath, niceTicks, seriesColour, } from "./chart-core.js";
|
|
7
|
+
const numberFormat = new Intl.NumberFormat(undefined, {
|
|
8
|
+
maximumFractionDigits: 2,
|
|
9
|
+
});
|
|
10
|
+
const defaultY = (n) => numberFormat.format(n);
|
|
11
|
+
const defaultX = (v) => v instanceof Date ? v.toLocaleDateString() : String(v ?? "");
|
|
12
|
+
/**
|
|
13
|
+
* A row's value for a series. Numbers pass through; numeric strings (common
|
|
14
|
+
* in JSON from APIs) are read as numbers; anything else is a missing value.
|
|
15
|
+
*/
|
|
16
|
+
const valueOf = (row, key) => {
|
|
17
|
+
const v = row[key];
|
|
18
|
+
if (typeof v === "number")
|
|
19
|
+
return v;
|
|
20
|
+
if (typeof v === "string" && v.trim() !== "") {
|
|
21
|
+
const n = Number(v);
|
|
22
|
+
return Number.isFinite(n) ? n : Number.NaN;
|
|
23
|
+
}
|
|
24
|
+
return Number.NaN;
|
|
25
|
+
};
|
|
26
|
+
/** At most eight series: slots are never reused, so a ninth is not drawn. */
|
|
27
|
+
const limitSeries = (series) => series.slice(0, 8);
|
|
28
|
+
/**
|
|
29
|
+
* One distinct slot per series. Pinned slots are kept (a repeated pin goes to
|
|
30
|
+
* the first free slot); unpinned series take the lowest slots nobody pinned.
|
|
31
|
+
*/
|
|
32
|
+
export function assignSlots(series) {
|
|
33
|
+
const taken = new Set();
|
|
34
|
+
const slots = series.map((s) => {
|
|
35
|
+
if (s.slot && !taken.has(s.slot)) {
|
|
36
|
+
taken.add(s.slot);
|
|
37
|
+
return s.slot;
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
});
|
|
41
|
+
let next = 1;
|
|
42
|
+
return slots.map((slot) => {
|
|
43
|
+
if (slot)
|
|
44
|
+
return slot;
|
|
45
|
+
while (taken.has(next))
|
|
46
|
+
next++;
|
|
47
|
+
taken.add(next);
|
|
48
|
+
return next;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const colour = (slot) => ({ "--m-series": seriesColour(slot) });
|
|
52
|
+
/**
|
|
53
|
+
* Diverging stack: per row, positive values stack up from zero and negative
|
|
54
|
+
* values stack down from zero, so layers never overlap. A missing value has
|
|
55
|
+
* no extent and leaves a gap. Returns [from, to] per series per row.
|
|
56
|
+
*/
|
|
57
|
+
function stack(rows, series) {
|
|
58
|
+
return rows.map((row) => {
|
|
59
|
+
let up = 0;
|
|
60
|
+
let down = 0;
|
|
61
|
+
return series.map((s) => {
|
|
62
|
+
const v = valueOf(row, s.key);
|
|
63
|
+
if (!Number.isFinite(v))
|
|
64
|
+
return [Number.NaN, Number.NaN];
|
|
65
|
+
if (v >= 0) {
|
|
66
|
+
const from = up;
|
|
67
|
+
up += v;
|
|
68
|
+
return [from, up];
|
|
69
|
+
}
|
|
70
|
+
const from = down;
|
|
71
|
+
down += v;
|
|
72
|
+
return [from, down];
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/** A bar with rounded corners on its data end only; the baseline end stays square. */
|
|
77
|
+
function barPath(x, y, w, h, up, r = 4) {
|
|
78
|
+
const radius = Math.max(0, Math.min(r, w / 2, h));
|
|
79
|
+
if (!radius)
|
|
80
|
+
return `M${x} ${y}h${w}v${h}h${-w}Z`;
|
|
81
|
+
return up
|
|
82
|
+
? `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`
|
|
83
|
+
: `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`;
|
|
84
|
+
}
|
|
85
|
+
// Plot margins in pixels. The top grows to fit a y axis label; the left grows
|
|
86
|
+
// with the widest y tick label.
|
|
87
|
+
const TOP = 12;
|
|
88
|
+
const LABELLED_TOP = 28;
|
|
89
|
+
const BOTTOM = 28;
|
|
90
|
+
const CHAR = 7;
|
|
91
|
+
// Below this width, line charts drop direct end labels and keep the legend.
|
|
92
|
+
const DIRECT_MIN_WIDTH = 400;
|
|
93
|
+
/** Container width, measured after layout; 640 until then (and on the server). */
|
|
94
|
+
function useWidth() {
|
|
95
|
+
const ref = useRef(null);
|
|
96
|
+
const [width, setWidth] = useState(640);
|
|
97
|
+
useLayoutEffect(() => {
|
|
98
|
+
const el = ref.current;
|
|
99
|
+
if (!el)
|
|
100
|
+
return;
|
|
101
|
+
const measure = () => {
|
|
102
|
+
const next = Math.round(el.getBoundingClientRect().width);
|
|
103
|
+
if (next > 0)
|
|
104
|
+
setWidth((old) => (old === next ? old : next));
|
|
105
|
+
};
|
|
106
|
+
measure();
|
|
107
|
+
const observer = new ResizeObserver(measure);
|
|
108
|
+
observer.observe(el);
|
|
109
|
+
return () => observer.disconnect();
|
|
110
|
+
}, []);
|
|
111
|
+
return [ref, width];
|
|
112
|
+
}
|
|
113
|
+
/** A clip-path id that is safe inside url(#…), from React's useId. */
|
|
114
|
+
const useClipId = () => `m-chart-clip-${useId().replace(/[^\w-]/g, "")}`;
|
|
115
|
+
function geometry(values, width, height, y, format, rightPad, zero) {
|
|
116
|
+
let [min, max] = extent(values);
|
|
117
|
+
if (y.min !== undefined)
|
|
118
|
+
min = y.min;
|
|
119
|
+
if (y.max !== undefined)
|
|
120
|
+
max = y.max;
|
|
121
|
+
// Bars measure from zero, so the axis always includes it, whatever y says.
|
|
122
|
+
if (zero) {
|
|
123
|
+
min = Math.min(0, min);
|
|
124
|
+
max = Math.max(0, max);
|
|
125
|
+
}
|
|
126
|
+
if (!(min < max)) {
|
|
127
|
+
// An inverted or flat override: fall back to the data, then to a unit
|
|
128
|
+
// span, keeping zero where the chart measures from it.
|
|
129
|
+
[min, max] = extent(values);
|
|
130
|
+
if (zero) {
|
|
131
|
+
min = Math.min(0, min);
|
|
132
|
+
max = Math.max(0, max);
|
|
133
|
+
}
|
|
134
|
+
if (min === max)
|
|
135
|
+
max = min + 1;
|
|
136
|
+
}
|
|
137
|
+
const ticks = niceTicks([min, max], Math.max(2, Math.floor(height / 48)));
|
|
138
|
+
const lo = Math.min(min, ticks[0]);
|
|
139
|
+
const hi = Math.max(max, ticks[ticks.length - 1]);
|
|
140
|
+
const left = Math.max(...ticks.map((t) => format(t).length)) * CHAR + 12;
|
|
141
|
+
const top = y.label ? LABELLED_TOP : TOP;
|
|
142
|
+
return {
|
|
143
|
+
width,
|
|
144
|
+
height,
|
|
145
|
+
left,
|
|
146
|
+
right: Math.max(left + 1, width - rightPad),
|
|
147
|
+
top,
|
|
148
|
+
bottom: height - BOTTOM,
|
|
149
|
+
ticks,
|
|
150
|
+
y: linearScale([lo, hi], [height - BOTTOM, top]),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Spreads end-of-line labels so none overlap and all stay between the plot's
|
|
155
|
+
* top and bottom: pushed down from the top, then back up from the bottom.
|
|
156
|
+
*/
|
|
157
|
+
export function spread(positions, top, bottom, gap = 14) {
|
|
158
|
+
const sorted = [...positions]
|
|
159
|
+
.map((p) => ({ ...p, y: Math.min(bottom, Math.max(top, p.y)) }))
|
|
160
|
+
.sort((a, b) => a.y - b.y);
|
|
161
|
+
for (let i = 1; i < sorted.length; i++)
|
|
162
|
+
sorted[i].y = Math.max(sorted[i].y, sorted[i - 1].y + gap);
|
|
163
|
+
for (let i = sorted.length - 1; i >= 0; i--) {
|
|
164
|
+
const limit = i === sorted.length - 1 ? bottom : sorted[i + 1].y - gap;
|
|
165
|
+
sorted[i].y = Math.max(top, Math.min(sorted[i].y, limit));
|
|
166
|
+
}
|
|
167
|
+
return new Map(sorted.map((p) => [p.key, p.y]));
|
|
168
|
+
}
|
|
169
|
+
/** x positions spread across the plot; a single row sits in the middle. */
|
|
170
|
+
const spreadX = (count, g) => count === 1
|
|
171
|
+
? [(g.left + g.right) / 2]
|
|
172
|
+
: Array.from({ length: count }, (_, i) => linearScale([0, count - 1], [g.left, g.right])(i));
|
|
173
|
+
/** A point with no known neighbour, which a line alone cannot show. */
|
|
174
|
+
const isolated = (points, j) => Number.isFinite(points[j].y) &&
|
|
175
|
+
!Number.isFinite(points[j - 1]?.y ?? Number.NaN) &&
|
|
176
|
+
!Number.isFinite(points[j + 1]?.y ?? Number.NaN);
|
|
177
|
+
/**
|
|
178
|
+
* The chart frame: a named figure with its description, legend, plot,
|
|
179
|
+
* tooltip, keyboard navigation and a table view of the same rows.
|
|
180
|
+
*/
|
|
181
|
+
function ChartFrame({ name, title, titleHidden = false, description, rows, x, series, slots, y = {}, legend = "auto", tableView = true, loading, error, empty = { title: "No data", description: "There is nothing to show yet." }, height = 240, id, className, plot, positions, }) {
|
|
182
|
+
const autoId = useId();
|
|
183
|
+
const titleId = `${autoId}-title`;
|
|
184
|
+
const descId = `${autoId}-desc`;
|
|
185
|
+
const [ref, width] = useWidth();
|
|
186
|
+
const [activeState, setActive] = useState(null);
|
|
187
|
+
// Only keyboard moves are announced: announcing every pointer move would
|
|
188
|
+
// flood a screen reader while the pointer crosses the chart.
|
|
189
|
+
const [announce, setAnnounce] = useState(false);
|
|
190
|
+
const [showTable, setShowTable] = useState(false);
|
|
191
|
+
// Rows can shrink while a point is active; never point past the end.
|
|
192
|
+
const active = activeState !== null && activeState < rows.length ? activeState : null;
|
|
193
|
+
const xFormat = x.format ?? defaultX;
|
|
194
|
+
const valueFormat = (s) => s.format ?? y.format ?? defaultY;
|
|
195
|
+
const xs = positions(width);
|
|
196
|
+
const describe = (index) => `${xFormat(rows[index][x.key])}: ${series
|
|
197
|
+
.map((s) => {
|
|
198
|
+
const v = valueOf(rows[index], s.key);
|
|
199
|
+
return `${s.label} ${Number.isFinite(v) ? valueFormat(s)(v) : "no value"}`;
|
|
200
|
+
})
|
|
201
|
+
.join(", ")}`;
|
|
202
|
+
const nearest = (px) => {
|
|
203
|
+
let best = 0;
|
|
204
|
+
for (let i = 1; i < xs.length; i++)
|
|
205
|
+
if (Math.abs(xs[i] - px) < Math.abs(xs[best] - px))
|
|
206
|
+
best = i;
|
|
207
|
+
return best;
|
|
208
|
+
};
|
|
209
|
+
const onPointerMove = (event) => {
|
|
210
|
+
const box = event.currentTarget.getBoundingClientRect();
|
|
211
|
+
if (!xs.length)
|
|
212
|
+
return;
|
|
213
|
+
setAnnounce(false);
|
|
214
|
+
setActive(nearest(event.clientX - box.left));
|
|
215
|
+
};
|
|
216
|
+
const onKeyDown = (event) => {
|
|
217
|
+
const last = rows.length - 1;
|
|
218
|
+
const moves = {
|
|
219
|
+
ArrowRight: Math.min(last, (active ?? -1) + 1),
|
|
220
|
+
ArrowLeft: Math.max(0, (active ?? 1) - 1),
|
|
221
|
+
Home: 0,
|
|
222
|
+
End: last,
|
|
223
|
+
};
|
|
224
|
+
if (event.key in moves && last >= 0) {
|
|
225
|
+
event.preventDefault();
|
|
226
|
+
setAnnounce(true);
|
|
227
|
+
setActive(moves[event.key]);
|
|
228
|
+
}
|
|
229
|
+
else if (event.key === "Escape")
|
|
230
|
+
setActive(null);
|
|
231
|
+
};
|
|
232
|
+
const body = loading ? (_jsx("p", { className: "m-chart-state", role: "status", children: "Loading chart\u2026" })) : error ? (_jsx(Notice, { title: "Unable to load chart", tone: "danger", announce: true, children: error })) : !rows.length ? (_jsx(EmptyState, { title: empty.title, description: empty.description })) : showTable ? (_jsx(Table, { caption: title, rowHeaders: true, columns: [
|
|
233
|
+
// Every column needs a name, even when x has no label.
|
|
234
|
+
{ key: "__x", label: x.label ?? x.key },
|
|
235
|
+
...series.map((s) => ({
|
|
236
|
+
key: s.key,
|
|
237
|
+
label: s.label,
|
|
238
|
+
align: "end",
|
|
239
|
+
})),
|
|
240
|
+
], rows: rows.map((row) => ({
|
|
241
|
+
__x: xFormat(row[x.key]),
|
|
242
|
+
...Object.fromEntries(series.map((s) => {
|
|
243
|
+
const v = valueOf(row, s.key);
|
|
244
|
+
return [s.key, Number.isFinite(v) ? valueFormat(s)(v) : "—"];
|
|
245
|
+
})),
|
|
246
|
+
})) })) : (_jsxs("div", { className: "m-chart-plot", tabIndex: 0, role: "group", "aria-labelledby": titleId, "aria-describedby": description ? descId : undefined, "aria-roledescription": "chart", onPointerMove: onPointerMove, onPointerLeave: () => setActive(null), onKeyDown: onKeyDown, onBlur: () => setActive(null), children: [_jsx("svg", { width: width, height: "100%", "aria-hidden": "true", focusable: "false", children: plot(width, active) }), active !== null && (_jsxs("div", { className: "m-chart-tooltip", style: { left: xs[active] }, "data-side": xs[active] > width / 2 ? "start" : "end", "aria-hidden": "true", children: [_jsx("strong", { children: xFormat(rows[active][x.key]) }), series.map((s, i) => {
|
|
247
|
+
const v = valueOf(rows[active], s.key);
|
|
248
|
+
return (_jsxs("span", { children: [_jsx("i", { style: colour(slots[i]) }), s.label, _jsx("b", { children: Number.isFinite(v) ? valueFormat(s)(v) : "—" })] }, s.key));
|
|
249
|
+
})] }))] }));
|
|
250
|
+
return (_jsxs("figure", { id: id, ...componentRoot(name), className: cx("m-chart", className), "aria-labelledby": titleId, children: [_jsxs("figcaption", { className: "m-chart-head", children: [_jsx("span", { id: titleId, className: titleHidden ? "m-sr-only" : "m-chart-title", children: title }), description && (_jsx("span", { id: descId, className: "m-chart-description", children: description }))] }), legend === "auto" && series.length > 1 && !showTable && (_jsx("ul", { className: "m-chart-legend", "aria-label": "Legend", children: series.map((s, i) => (_jsx("li", { style: colour(slots[i]), children: s.label }, s.key))) })), _jsx("div", { ref: ref, className: "m-chart-body", style: showTable ? undefined : { height }, children: body }), _jsx("p", { className: "m-sr-only", "aria-live": "polite", children: announce && active !== null ? describe(active) : "" }), tableView && rows.length > 0 && !loading && !error && (_jsx("div", { className: "m-chart-actions", children: _jsx(Button, { variant: "ghost", onClick: () => setShowTable((v) => !v), children: showTable ? "Show chart" : "Show data" }) }))] }));
|
|
251
|
+
}
|
|
252
|
+
/** Gridlines, y labels and the y axis label for a geometry. */
|
|
253
|
+
function YAxis({ g, format, label, }) {
|
|
254
|
+
return (_jsxs("g", { className: "m-chart-axis", "aria-hidden": "true", children: [label && (_jsx("text", { className: "m-chart-axis-label", x: 0, y: 12, children: label })), g.ticks.map((t) => (_jsxs("g", { children: [_jsx("line", { x1: g.left, x2: g.right, y1: g.y(t), y2: g.y(t) }), _jsx("text", { x: g.left - 8, y: g.y(t), dy: "0.32em", textAnchor: "end", children: format(t) })] }, t)))] }));
|
|
255
|
+
}
|
|
256
|
+
/** Category labels along the bottom, thinned so they never overlap. */
|
|
257
|
+
function XLabels({ xs, labels, g, }) {
|
|
258
|
+
const longest = Math.max(1, ...labels.map((l) => l.length)) * CHAR + 12;
|
|
259
|
+
const step = Math.max(1, Math.ceil(longest / Math.max(1, (g.right - g.left) / Math.max(1, xs.length))));
|
|
260
|
+
return (_jsx("g", { className: "m-chart-axis", "aria-hidden": "true", children: xs.map((x, i) => i % step === 0 ? (_jsx("text", { x: x, y: g.height - 8, textAnchor: "middle", children: labels[i] }, i)) : null) }));
|
|
261
|
+
}
|
|
262
|
+
/** Clips marks to the plot, so a y min or max inside the data never spills. */
|
|
263
|
+
function PlotClip({ id, g }) {
|
|
264
|
+
return (_jsx("clipPath", { id: id, children: _jsx("rect", { x: g.left - 6, y: g.top - 6, width: g.right - g.left + 12, height: g.bottom - g.top + 12 }) }));
|
|
265
|
+
}
|
|
266
|
+
/** Change over time for one to eight series, with direct end labels for up to four. */
|
|
267
|
+
export function LineChart(input) {
|
|
268
|
+
const props = { ...input, series: limitSeries(input.series) };
|
|
269
|
+
const { rows, x, series, y = {}, height = 240, markers = false } = props;
|
|
270
|
+
const format = y.format ?? defaultY;
|
|
271
|
+
const slots = assignSlots(series);
|
|
272
|
+
const clipId = useClipId();
|
|
273
|
+
const values = rows.flatMap((row) => series.map((s) => valueOf(row, s.key)));
|
|
274
|
+
const layout = (width) => {
|
|
275
|
+
const direct = series.length > 1 && series.length <= 4 && width >= DIRECT_MIN_WIDTH;
|
|
276
|
+
const labelWidth = direct
|
|
277
|
+
? Math.min(width * 0.3, Math.max(...series.map((s) => s.label.length)) * CHAR + 16)
|
|
278
|
+
: 12;
|
|
279
|
+
const g = geometry(values, width, height, y, format, labelWidth, false);
|
|
280
|
+
return { g, direct, xs: spreadX(rows.length, g) };
|
|
281
|
+
};
|
|
282
|
+
return (_jsx(ChartFrame, { ...props, slots: slots, name: "LineChart", className: cx("m-line-chart", props.className), positions: (width) => layout(width).xs, plot: (width, active) => {
|
|
283
|
+
const { g, direct, xs } = layout(width);
|
|
284
|
+
const lines = series.map((s, i) => ({
|
|
285
|
+
s,
|
|
286
|
+
slot: slots[i],
|
|
287
|
+
points: rows.map((row, j) => ({
|
|
288
|
+
x: xs[j],
|
|
289
|
+
y: g.y(valueOf(row, s.key)),
|
|
290
|
+
})),
|
|
291
|
+
}));
|
|
292
|
+
const ends = spread(lines.flatMap(({ s, points }) => {
|
|
293
|
+
const last = [...points]
|
|
294
|
+
.reverse()
|
|
295
|
+
.find((p) => Number.isFinite(p.y));
|
|
296
|
+
// A line whose end is clipped out of the plot gets no label.
|
|
297
|
+
return last && last.y >= g.top && last.y <= g.bottom
|
|
298
|
+
? [{ key: s.key, y: last.y }]
|
|
299
|
+
: [];
|
|
300
|
+
}), g.top, g.bottom);
|
|
301
|
+
return (_jsxs("g", { children: [_jsx(PlotClip, { id: clipId, g: g }), _jsx(YAxis, { g: g, format: format, label: y.label }), _jsx(XLabels, { xs: xs, labels: rows.map((r) => (x.format ?? defaultX)(r[x.key])), g: g }), active !== null && (_jsx("line", { className: "m-chart-crosshair", x1: xs[active], x2: xs[active], y1: g.top, y2: g.bottom })), lines.map(({ s, slot, points }) => (_jsxs("g", { style: colour(slot), children: [_jsxs("g", { clipPath: `url(#${clipId})`, children: [_jsx("path", { className: "m-chart-line", d: linePath(points) }), points.map((p, j) => Number.isFinite(p.y) &&
|
|
302
|
+
(markers || j === active || isolated(points, j)) ? (_jsx("circle", { className: "m-chart-marker", cx: p.x, cy: p.y, r: "4" }, j)) : null)] }), direct && ends.has(s.key) && (_jsx("text", { className: "m-chart-end-label", x: g.right + 8, y: ends.get(s.key), dy: "0.32em", children: s.label }))] }, s.key)))] }));
|
|
303
|
+
} }));
|
|
304
|
+
}
|
|
305
|
+
/** Change over time where volume matters; stacked when the series sum to a whole. */
|
|
306
|
+
export function AreaChart(input) {
|
|
307
|
+
const props = { ...input, series: limitSeries(input.series) };
|
|
308
|
+
const { rows, series, y = {}, height = 240, stacked = true } = props;
|
|
309
|
+
const format = y.format ?? defaultY;
|
|
310
|
+
const slots = assignSlots(series);
|
|
311
|
+
const clipId = useClipId();
|
|
312
|
+
const fill = stacked || series.length === 1;
|
|
313
|
+
// [from, to] per row and series: a diverging stack, or zero to the value.
|
|
314
|
+
const layers = stacked
|
|
315
|
+
? stack(rows, series)
|
|
316
|
+
: rows.map((row) => series.map((s) => [0, valueOf(row, s.key)]));
|
|
317
|
+
const values = layers.flat(2).concat(0);
|
|
318
|
+
const layout = (width) => {
|
|
319
|
+
const g = geometry(values, width, height, y, format, 12, true);
|
|
320
|
+
return { g, xs: spreadX(rows.length, g) };
|
|
321
|
+
};
|
|
322
|
+
return (_jsx(ChartFrame, { ...props, slots: slots, name: "AreaChart", className: cx("m-area-chart", props.className), positions: (width) => layout(width).xs, plot: (width, active) => {
|
|
323
|
+
const { g, xs } = layout(width);
|
|
324
|
+
return (_jsxs("g", { children: [_jsx(PlotClip, { id: clipId, g: g }), _jsx(YAxis, { g: g, format: format, label: y.label }), _jsx(XLabels, { xs: xs, labels: rows.map((r) => (props.x.format ?? defaultX)(r[props.x.key])), g: g }), _jsx("g", { clipPath: `url(#${clipId})`, children: series.map((s, i) => {
|
|
325
|
+
const end = rows.map((_, j) => ({
|
|
326
|
+
x: xs[j],
|
|
327
|
+
y: g.y(layers[j][i][1]),
|
|
328
|
+
}));
|
|
329
|
+
const start = rows.map((_, j) => ({
|
|
330
|
+
x: xs[j],
|
|
331
|
+
y: Number.isFinite(layers[j][i][1])
|
|
332
|
+
? g.y(layers[j][i][0])
|
|
333
|
+
: Number.NaN,
|
|
334
|
+
}));
|
|
335
|
+
return (_jsxs("g", { style: colour(slots[i]), children: [fill && (_jsx("path", { className: "m-chart-area", d: bandPath(end, start) })), _jsx("path", { className: "m-chart-line", d: linePath(end) }), end.map((p, j) => Number.isFinite(p.y) &&
|
|
336
|
+
(j === active || isolated(end, j)) ? (_jsx("circle", { className: "m-chart-marker", cx: p.x, cy: p.y, r: "4" }, j)) : null)] }, s.key));
|
|
337
|
+
}) }), active !== null && (_jsx("line", { className: "m-chart-crosshair", x1: xs[active], x2: xs[active], y1: g.top, y2: g.bottom }))] }));
|
|
338
|
+
} }));
|
|
339
|
+
}
|
|
340
|
+
/** Compares values across categories. Bars always start at zero. */
|
|
341
|
+
export function BarChart(input) {
|
|
342
|
+
const props = { ...input, series: limitSeries(input.series) };
|
|
343
|
+
const { rows, series, y = {}, height = 240, layout = "grouped" } = props;
|
|
344
|
+
const format = y.format ?? defaultY;
|
|
345
|
+
const slots = assignSlots(series);
|
|
346
|
+
const clipId = useClipId();
|
|
347
|
+
const stacked = layout === "stacked" && series.length > 1;
|
|
348
|
+
// [from, to] per row and series: a diverging stack, or zero to the value.
|
|
349
|
+
const layers = stacked
|
|
350
|
+
? stack(rows, series)
|
|
351
|
+
: rows.map((row) => series.map((s) => [0, valueOf(row, s.key)]));
|
|
352
|
+
const values = layers.flat(2).concat(0);
|
|
353
|
+
// The outermost segment on each side of zero carries the rounded data end.
|
|
354
|
+
const ends = layers.map((row) => {
|
|
355
|
+
let up = -1;
|
|
356
|
+
let down = -1;
|
|
357
|
+
row.forEach(([from, to], i) => {
|
|
358
|
+
if (to > from)
|
|
359
|
+
up = i;
|
|
360
|
+
else if (to < from)
|
|
361
|
+
down = i;
|
|
362
|
+
});
|
|
363
|
+
return { up, down };
|
|
364
|
+
});
|
|
365
|
+
const band = (width) => {
|
|
366
|
+
const g = geometry(values, width, height, y, format, 12, true);
|
|
367
|
+
const step = (g.right - g.left) / Math.max(1, rows.length);
|
|
368
|
+
const xs = rows.map((_, i) => g.left + step * (i + 0.5));
|
|
369
|
+
return { g, step, xs, bar: Math.min(48, step * 0.7) };
|
|
370
|
+
};
|
|
371
|
+
return (_jsx(ChartFrame, { ...props, slots: slots, name: "BarChart", className: cx("m-bar-chart", props.className), positions: (width) => band(width).xs, plot: (width, active) => {
|
|
372
|
+
const { g, step, xs, bar } = band(width);
|
|
373
|
+
const zero = g.y(0);
|
|
374
|
+
const groupWidth = stacked ? bar : bar / series.length;
|
|
375
|
+
return (_jsxs("g", { children: [_jsx(PlotClip, { id: clipId, g: g }), _jsx(YAxis, { g: g, format: format, label: y.label }), _jsx(XLabels, { xs: xs, labels: rows.map((r) => (props.x.format ?? defaultX)(r[props.x.key])), g: g }), _jsx("g", { clipPath: `url(#${clipId})`, children: layers.map((row, j) => (_jsxs("g", { "data-active": active === j || undefined, children: [active === j && (_jsx("rect", { className: "m-chart-band", x: xs[j] - step / 2, width: step, y: g.top, height: g.bottom - g.top })), row.map(([from, to], i) => {
|
|
376
|
+
if (!Number.isFinite(to) || to === from)
|
|
377
|
+
return null;
|
|
378
|
+
const left = stacked
|
|
379
|
+
? xs[j] - bar / 2
|
|
380
|
+
: xs[j] - bar / 2 + i * groupWidth;
|
|
381
|
+
const top = Math.min(g.y(from), g.y(to));
|
|
382
|
+
const h = Math.abs(g.y(to) - g.y(from));
|
|
383
|
+
const w = Math.max(1, groupWidth - (stacked ? 0 : 2));
|
|
384
|
+
const up = to > from;
|
|
385
|
+
// Every grouped bar is its own data end; in a stack only
|
|
386
|
+
// the outermost segment on each side of zero is.
|
|
387
|
+
const isEnd = !stacked || (up ? ends[j].up === i : ends[j].down === i);
|
|
388
|
+
return (_jsx("path", { className: "m-chart-bar", style: colour(slots[i]), d: barPath(left + (stacked ? 0 : 1), top, w, h, up, isEnd ? 4 : 0) }, series[i].key));
|
|
389
|
+
})] }, j))) }), _jsx("line", { className: "m-chart-zero", x1: g.left, x2: g.right, y1: zero, y2: zero })] }));
|
|
390
|
+
} }));
|
|
391
|
+
}
|
package/docs/charts.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Charts
|
|
2
2
|
|
|
3
|
-
`@tonycodes-ui/mortar/charts` draws charts as SVG with Mortar's tokens, so they follow your brand, density and light or dark appearance. It has no runtime dependencies. This release has `Sparkline
|
|
3
|
+
`@tonycodes-ui/mortar/charts` draws charts as SVG with Mortar's tokens, so they follow your brand, density and light or dark appearance. It has no runtime dependencies. This release has `Sparkline`, `LineChart`, `AreaChart` and `BarChart`; a meter is planned.
|
|
4
4
|
|
|
5
5
|
## Sparkline
|
|
6
6
|
|
|
@@ -38,8 +38,51 @@ import { Sparkline } from "@tonycodes-ui/mortar/charts";
|
|
|
38
38
|
/>
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
## Line, area and bar charts
|
|
42
|
+
|
|
43
|
+
`LineChart`, `AreaChart` and `BarChart` take rows and a list of series that name the field each one plots, so data from an API needs no reshaping. Series fields may be numbers or numeric strings such as `"42.5"`; anything else (`null`, `""`, `"n/a"`) is a missing value and leaves a gap.
|
|
44
|
+
|
|
45
|
+
```tsx
|
|
46
|
+
import { LineChart } from "@tonycodes-ui/mortar/charts";
|
|
47
|
+
|
|
48
|
+
<LineChart
|
|
49
|
+
title="Monthly revenue by plan"
|
|
50
|
+
description="Revenue in thousands of dollars, January to June 2026."
|
|
51
|
+
rows={months}
|
|
52
|
+
x={{ key: "month", label: "Month" }}
|
|
53
|
+
series={[
|
|
54
|
+
{ key: "pro", label: "Pro" },
|
|
55
|
+
{ key: "team", label: "Team" },
|
|
56
|
+
]}
|
|
57
|
+
y={{ format: (n) => `$${n}k` }}
|
|
58
|
+
/>;
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
| Chart | Use it for | Options |
|
|
62
|
+
| ----------- | ---------------------------------------------------------------- | ------------------------------------------------------------- |
|
|
63
|
+
| `LineChart` | Change over time, one to eight series | `markers` puts a dot on every value |
|
|
64
|
+
| `AreaChart` | Change over time when the series add up to a meaningful total | `stacked` (default true); unstacked series draw as lines only |
|
|
65
|
+
| `BarChart` | Comparing values across categories or a few periods; starts at 0 | `layout`: `grouped` (default) or `stacked` |
|
|
66
|
+
|
|
67
|
+
- `title` is required: it names the chart for screen readers and shows above it (`titleHidden` hides it visually). `description` is one sentence on what the chart shows.
|
|
68
|
+
- `x.format`, `y.format` and each series' `format` control how values read in the axis, tooltip and table. `y.label` names the axis and its unit above the plot, for example "Revenue ($k)".
|
|
69
|
+
- `y.min` and `y.max` fix the axis range; marks outside it are clipped to the plot. Bar charts always include zero.
|
|
70
|
+
- Stacks diverge: positive values stack up from zero and negative values stack down from it, so layers never overlap. A missing value leaves a gap rather than dropping to zero.
|
|
71
|
+
- `height` sets the plot height (default 240 pixels); the width follows the container. Below 400 pixels wide, line charts drop their end labels and keep the legend.
|
|
72
|
+
- `loading`, `error` and `empty` show the same states as tables.
|
|
73
|
+
- Charts draw at most eight series, each with its own colour. A pinned `slot` is never reused: series without one take the lowest free slots. Fold anything past eight into "Other", or split it across charts.
|
|
74
|
+
- Never put two measures with different scales on one chart. Use two charts instead.
|
|
75
|
+
|
|
41
76
|
## Accessibility
|
|
42
77
|
|
|
78
|
+
Every line, area and bar chart is a named figure:
|
|
79
|
+
|
|
80
|
+
- A legend names every series when there are two or more, and a line chart labels up to four lines at their ends, so identity never depends on colour.
|
|
81
|
+
- The plot takes one tab stop. Left and Right move between x values, Home and End jump to the first and last, and Escape closes the tooltip. Each keyboard move is announced, for example "Apr: Pro $51k, Team $29k"; pointer movement shows the tooltip without announcing.
|
|
82
|
+
- **Show data** swaps the plot for a table of the same rows with formatted values, and **Show chart** swaps back.
|
|
83
|
+
- Text uses the text tokens; marks keep a surface-coloured gap or ring where they meet.
|
|
84
|
+
- In high-contrast (forced colours) mode, series keep their colours so they stay distinguishable, and axes and labels follow the system colours.
|
|
85
|
+
|
|
43
86
|
A sparkline is an image with a spoken summary built from `label` and the values: "Revenue, last 12 months: 12 values from $42k to $75k, latest $75k". Give `label` the measure and the period, and pass `format` so the summary reads like the number beside it. The summary never depends on colour, and the line keeps its shape in forced-colours mode.
|
|
44
87
|
|
|
45
88
|
## Colour
|
package/package.json
CHANGED
package/src/chart-core.ts
CHANGED
|
@@ -103,6 +103,35 @@ export function areaPath(points: readonly Point[], baseline: number): string {
|
|
|
103
103
|
return d;
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
/** SVG path data for the band between an upper and a lower edge (a stacked layer). */
|
|
107
|
+
export function bandPath(
|
|
108
|
+
upper: readonly Point[],
|
|
109
|
+
lower: readonly Point[],
|
|
110
|
+
): string {
|
|
111
|
+
// One closed shape per run where both edges are known, so a missing value
|
|
112
|
+
// leaves a gap instead of a fill bridging it.
|
|
113
|
+
let d = "";
|
|
114
|
+
let run: (readonly [Point, Point])[] = [];
|
|
115
|
+
const close = () => {
|
|
116
|
+
if (run.length >= 2) {
|
|
117
|
+
const back = run
|
|
118
|
+
.map(([, l]) => l)
|
|
119
|
+
.reverse()
|
|
120
|
+
.map((p) => `L${round(p.x)} ${round(p.y)}`)
|
|
121
|
+
.join("");
|
|
122
|
+
d += `${linePath(run.map(([u]) => u))}${back}Z`;
|
|
123
|
+
}
|
|
124
|
+
run = [];
|
|
125
|
+
};
|
|
126
|
+
upper.forEach((u, i) => {
|
|
127
|
+
const l = lower[i];
|
|
128
|
+
if (Number.isFinite(u.y) && l && Number.isFinite(l.y)) run.push([u, l]);
|
|
129
|
+
else close();
|
|
130
|
+
});
|
|
131
|
+
close();
|
|
132
|
+
return d;
|
|
133
|
+
}
|
|
134
|
+
|
|
106
135
|
const round = (n: number) => Math.round(n * 100) / 100;
|
|
107
136
|
|
|
108
137
|
/** A categorical series slot. There are eight and they are never reused: a
|