@tonycodes-ui/mortar 0.29.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 +6 -18
- package/catalog.json +859 -361
- package/cli/audit.mjs +1 -1
- package/cli/data.mjs +5 -0
- package/cli/packet.mjs +2 -0
- package/dist/agent-data.json +1 -1
- package/dist/application.d.ts +2 -0
- package/dist/application.js +2 -1
- package/dist/chart-core.d.ts +32 -0
- package/dist/chart-core.js +127 -0
- package/dist/charts.d.ts +5 -0
- package/dist/charts.js +4 -0
- package/dist/sparkline.d.ts +28 -0
- package/dist/sparkline.js +31 -0
- package/dist/xy-chart.d.ts +86 -0
- package/dist/xy-chart.js +391 -0
- package/docs/charts.md +111 -0
- package/package.json +5 -1
- package/src/application.css +6 -1
- package/src/application.tsx +10 -0
- package/src/chart-core.ts +142 -0
- package/src/charts.css +239 -0
- package/src/charts.ts +16 -0
- package/src/sparkline.tsx +124 -0
- package/src/tokens.css +26 -0
- package/src/xy-chart.tsx +886 -0
- package/styles.css +1 -0
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
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Charts
|
|
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`, `LineChart`, `AreaChart` and `BarChart`; a meter is planned.
|
|
4
|
+
|
|
5
|
+
## Sparkline
|
|
6
|
+
|
|
7
|
+
A sparkline is a small trend line with no axes. Use it beside a number to show which way the number has been moving: in a stat tile, a table cell or a list row. When people need to read values off the chart, use a full chart instead.
|
|
8
|
+
|
|
9
|
+
```tsx
|
|
10
|
+
import { Sparkline } from "@tonycodes-ui/mortar/charts";
|
|
11
|
+
|
|
12
|
+
<Sparkline
|
|
13
|
+
label="Revenue, last 12 months"
|
|
14
|
+
values={[42, 45, 44, 51, 49, 56, 61, 58, 64, 70, 68, 75]}
|
|
15
|
+
format={(n) => `$${n}k`}
|
|
16
|
+
area
|
|
17
|
+
/>;
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- `values` are in order, oldest first. A missing value (`NaN`) leaves a gap in the line rather than joining across it.
|
|
21
|
+
- The width follows the container; `height` defaults to 32 pixels.
|
|
22
|
+
- `showLast` (on by default) marks the latest value with a dot. `area` fills under the line. `band` shades a reference range, such as a target or a normal range.
|
|
23
|
+
- `slot` picks the series colour (1 to 8, default 1); see [Colour](#colour).
|
|
24
|
+
|
|
25
|
+
`MetricGroup` items take a `sparkline` of recent values and draw it under the value, so a stat tile with a trend needs no extra layout:
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
<MetricGroup
|
|
29
|
+
label="Summary"
|
|
30
|
+
items={[
|
|
31
|
+
{
|
|
32
|
+
label: "Requests",
|
|
33
|
+
value: "1.42M",
|
|
34
|
+
change: "+12.4%",
|
|
35
|
+
sparkline: requestsByWeek,
|
|
36
|
+
},
|
|
37
|
+
]}
|
|
38
|
+
/>
|
|
39
|
+
```
|
|
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
|
+
|
|
76
|
+
## Accessibility
|
|
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
|
+
|
|
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.
|
|
87
|
+
|
|
88
|
+
## Colour
|
|
89
|
+
|
|
90
|
+
Series use eight colour tokens, `--m-chart-1` to `--m-chart-8`, in a fixed order:
|
|
91
|
+
|
|
92
|
+
| Slot | Hue | Light | Dark |
|
|
93
|
+
| ---- | ------- | --------- | --------- |
|
|
94
|
+
| 1 | blue | `#2a78d6` | `#3987e5` |
|
|
95
|
+
| 2 | orange | `#eb6834` | `#d95926` |
|
|
96
|
+
| 3 | aqua | `#1baf7a` | `#199e70` |
|
|
97
|
+
| 4 | yellow | `#eda100` | `#c98500` |
|
|
98
|
+
| 5 | magenta | `#e87ba4` | `#d55181` |
|
|
99
|
+
| 6 | green | `#008300` | `#0ca30c` |
|
|
100
|
+
| 7 | violet | `#6250d6` | `#9085e9` |
|
|
101
|
+
| 8 | red | `#e34948` | `#e66767` |
|
|
102
|
+
|
|
103
|
+
The palette was checked against Mortar's light and dark surfaces for colour-blind separation between neighbouring slots, a consistent lightness band and enough saturation to tell the hues apart. The dark column is the same hues stepped for the dark surface, not an automatic inversion. `tests/charts.test.mjs` pins the values, so changing one means checking the palette again.
|
|
104
|
+
|
|
105
|
+
Rules that keep charts readable:
|
|
106
|
+
|
|
107
|
+
- Give a series the same slot everywhere it appears, and keep it when other series are hidden.
|
|
108
|
+
- There are eight slots and they are never reused. A ninth series belongs in "Other" or in a separate chart.
|
|
109
|
+
- Series colours carry identity only. Success, warning, danger and info stay the status tones, shown with a label or icon, and are never a series colour.
|
|
110
|
+
- Text uses the text tokens, never a series colour.
|
|
111
|
+
- On white, slots 3, 4 and 5 are below 3:1 contrast, so a chart that uses them needs labels or a data table beside it.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tonycodes-ui/mortar",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.31.0",
|
|
4
4
|
"description": "Mortar: a shared design foundation, application and marketing UI for React and Tailwind.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -57,6 +57,10 @@
|
|
|
57
57
|
"./data-grid": {
|
|
58
58
|
"types": "./dist/data-grid.d.ts",
|
|
59
59
|
"import": "./dist/data-grid.js"
|
|
60
|
+
},
|
|
61
|
+
"./charts": {
|
|
62
|
+
"types": "./dist/charts.d.ts",
|
|
63
|
+
"import": "./dist/charts.js"
|
|
60
64
|
}
|
|
61
65
|
},
|
|
62
66
|
"sideEffects": [
|
package/src/application.css
CHANGED
|
@@ -579,7 +579,8 @@
|
|
|
579
579
|
letter-spacing: var(--m-tracking-heading);
|
|
580
580
|
font-variant-numeric: tabular-nums;
|
|
581
581
|
}
|
|
582
|
-
.
|
|
582
|
+
/* Not a nested Sparkline's own spans: that would block and offset them. */
|
|
583
|
+
.m-metrics span:where(:not(.m-sparkline, .m-sparkline *)) {
|
|
583
584
|
display: block;
|
|
584
585
|
margin-top: 4px;
|
|
585
586
|
font: 12px var(--m-mono);
|
|
@@ -617,6 +618,10 @@
|
|
|
617
618
|
.m-metrics span[data-trend] svg {
|
|
618
619
|
flex-shrink: 0;
|
|
619
620
|
}
|
|
621
|
+
.m-metrics .m-sparkline {
|
|
622
|
+
display: block;
|
|
623
|
+
margin-top: 12px;
|
|
624
|
+
}
|
|
620
625
|
.m-metrics[data-variant="cards"] {
|
|
621
626
|
gap: 16px;
|
|
622
627
|
border: 0;
|
package/src/application.tsx
CHANGED
|
@@ -11,6 +11,7 @@ import { Button, EmptyState, Input, Notice, type Tone } from "./primitives.js";
|
|
|
11
11
|
import { BrandMark, Divider } from "./layout.js";
|
|
12
12
|
import { AuthHeader, ProviderButtons, type SignInProvider } from "./auth.js";
|
|
13
13
|
import { ArrowDown, ArrowUp, Check, SortArrows } from "./icons.js";
|
|
14
|
+
import { Sparkline } from "./sparkline.js";
|
|
14
15
|
import { headingTag, type HeadingLevel } from "./heading.js";
|
|
15
16
|
import {
|
|
16
17
|
Flyout,
|
|
@@ -649,6 +650,8 @@ export interface MetricGroupProps {
|
|
|
649
650
|
trend?: "up" | "down";
|
|
650
651
|
/** Prior value for comparison, shown as "from …" after the value. */
|
|
651
652
|
previous?: string;
|
|
653
|
+
/** Recent values, oldest first, drawn as a sparkline under the value. */
|
|
654
|
+
sparkline?: number[];
|
|
652
655
|
}[];
|
|
653
656
|
/** `shared` joins metrics with shared borders; `cards` separates them into individual cards. */
|
|
654
657
|
variant?: "shared" | "cards";
|
|
@@ -703,6 +706,13 @@ export function MetricGroup({
|
|
|
703
706
|
{item.change}
|
|
704
707
|
</span>
|
|
705
708
|
)}
|
|
709
|
+
{item.sparkline?.length ? (
|
|
710
|
+
<Sparkline
|
|
711
|
+
label={`${item.label}, recent values`}
|
|
712
|
+
values={item.sparkline}
|
|
713
|
+
height={28}
|
|
714
|
+
/>
|
|
715
|
+
) : null}
|
|
706
716
|
</>
|
|
707
717
|
),
|
|
708
718
|
}))}
|