@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.
@@ -187,6 +187,8 @@ export interface MetricGroupProps {
187
187
  trend?: "up" | "down";
188
188
  /** Prior value for comparison, shown as "from …" after the value. */
189
189
  previous?: string;
190
+ /** Recent values, oldest first, drawn as a sparkline under the value. */
191
+ sparkline?: number[];
190
192
  }[];
191
193
  /** `shared` joins metrics with shared borders; `cards` separates them into individual cards. */
192
194
  variant?: "shared" | "cards";
@@ -5,6 +5,7 @@ import { Button, EmptyState, Input, Notice } from "./primitives.js";
5
5
  import { BrandMark, Divider } from "./layout.js";
6
6
  import { AuthHeader, ProviderButtons } from "./auth.js";
7
7
  import { ArrowDown, ArrowUp, Check, SortArrows } from "./icons.js";
8
+ import { Sparkline } from "./sparkline.js";
8
9
  import { Flyout, LinkContent, NavGroups, NavTreeLinks, MobileNavDialog, TermList, cx, componentRoot, classedIntroSlots, sectionTone, useDomId, } from "./internal.js";
9
10
  function SidebarContent({ brand, logo, workspace, homeHref, navigation, sections = [], footer, label = "Primary", onNavigate, }) {
10
11
  return (_jsxs(_Fragment, { children: [brand && (_jsxs(KitLink, { className: "m-workspace", href: homeHref || navigation[0]?.href || "#", children: [_jsx(BrandMark, { logo: logo }), _jsxs("span", { children: [_jsx("strong", { children: brand }), workspace && _jsx("small", { children: workspace })] })] })), _jsxs("nav", { "aria-label": label, children: [_jsx(NavTreeLinks, { items: navigation, marker: true, onNavigate: onNavigate }), _jsx(NavGroups, { groups: sections, marker: true, onNavigate: onNavigate })] }), footer && _jsx("div", { className: "m-user", children: footer })] }));
@@ -84,7 +85,7 @@ export function MetricGroup({ label, items, variant = "shared", className, }) {
84
85
  return (_jsx(TermList, { ...componentRoot("MetricGroup"), className: cx("m-metrics", className), "aria-label": label, "data-variant": variant === "cards" ? "cards" : undefined, items: items.map((item) => ({
85
86
  key: item.label,
86
87
  term: (_jsxs(_Fragment, { children: [item.icon && (_jsx("span", { className: "m-metric-icon", "aria-hidden": "true", children: item.icon })), item.label] })),
87
- details: (_jsxs(_Fragment, { children: [_jsx("strong", { children: item.value }), item.previous && (_jsxs("span", { className: "m-metric-previous", children: ["from ", item.previous] })), item.change && (_jsxs("span", { className: "m-metric-change", "data-tone": item.tone && item.tone !== "neutral" ? item.tone : undefined, "data-trend": item.trend, children: [item.trend && (_jsxs(_Fragment, { children: [item.trend === "up" ? _jsx(ArrowUp, {}) : _jsx(ArrowDown, {}), _jsx("span", { className: "m-sr-only", children: item.trend === "up" ? "Increased by " : "Decreased by " })] })), item.change] }))] })),
88
+ details: (_jsxs(_Fragment, { children: [_jsx("strong", { children: item.value }), item.previous && (_jsxs("span", { className: "m-metric-previous", children: ["from ", item.previous] })), item.change && (_jsxs("span", { className: "m-metric-change", "data-tone": item.tone && item.tone !== "neutral" ? item.tone : undefined, "data-trend": item.trend, children: [item.trend && (_jsxs(_Fragment, { children: [item.trend === "up" ? _jsx(ArrowUp, {}) : _jsx(ArrowDown, {}), _jsx("span", { className: "m-sr-only", children: item.trend === "up" ? "Increased by " : "Decreased by " })] })), item.change] })), item.sparkline?.length ? (_jsx(Sparkline, { label: `${item.label}, recent values`, values: item.sparkline, height: 28 })) : null] })),
88
89
  })) }));
89
90
  }
90
91
  import { columnAlign, columnLayout, groupRows, SelectAll, sortRows, TableGroupRow, } from "./table-core.js";
@@ -0,0 +1,32 @@
1
+ export type Extent = readonly [number, number];
2
+ /** Smallest and largest finite value; [0, 0] when there are none. */
3
+ export declare function extent(values: readonly number[]): Extent;
4
+ /**
5
+ * Maps a domain onto a range linearly. A flat domain maps to the range's
6
+ * middle. A missing value (NaN) stays missing, so lines keep their gaps.
7
+ */
8
+ export declare function linearScale(domain: Extent, range: Extent): (value: number) => number;
9
+ /**
10
+ * "Nice" tick values from the step at or below the minimum to the first step
11
+ * at or above the maximum, so the top gridline is never below the data.
12
+ * Inverted, non-finite and degenerate domains still return a short list.
13
+ */
14
+ export declare function niceTicks(domain: Extent, count?: number): number[];
15
+ export interface Point {
16
+ x: number;
17
+ y: number;
18
+ }
19
+ /** SVG path data for a polyline through the points; breaks at non-finite y. */
20
+ export declare function linePath(points: readonly Point[]): string;
21
+ /**
22
+ * SVG path data for the area between a line and a baseline y: one closed
23
+ * shape per run of finite values, so a missing value leaves a gap.
24
+ */
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;
28
+ /** A categorical series slot. There are eight and they are never reused: a
29
+ ninth series belongs in "Other" or in its own chart. */
30
+ export type ChartSlot = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
31
+ /** The CSS colour of a series slot, from the --m-chart-* tokens. */
32
+ export declare const seriesColour: (slot: ChartSlot) => string;
@@ -0,0 +1,127 @@
1
+ // Scales and path builders shared by Mortar's charts. Internal: the charts
2
+ // entry and MetricGroup use it; nothing here is exported from a package entry.
3
+ /** Smallest and largest finite value; [0, 0] when there are none. */
4
+ export function extent(values) {
5
+ let min = Infinity;
6
+ let max = -Infinity;
7
+ for (const v of values)
8
+ if (Number.isFinite(v)) {
9
+ if (v < min)
10
+ min = v;
11
+ if (v > max)
12
+ max = v;
13
+ }
14
+ return min === Infinity ? [0, 0] : [min, max];
15
+ }
16
+ /**
17
+ * Maps a domain onto a range linearly. A flat domain maps to the range's
18
+ * middle. A missing value (NaN) stays missing, so lines keep their gaps.
19
+ */
20
+ export function linearScale(domain, range) {
21
+ const [d0, d1] = domain;
22
+ const [r0, r1] = range;
23
+ const span = d1 - d0;
24
+ return (value) => !Number.isFinite(value)
25
+ ? Number.NaN
26
+ : span === 0
27
+ ? (r0 + r1) / 2
28
+ : r0 + ((value - d0) / span) * (r1 - r0);
29
+ }
30
+ /**
31
+ * "Nice" tick values from the step at or below the minimum to the first step
32
+ * at or above the maximum, so the top gridline is never below the data.
33
+ * Inverted, non-finite and degenerate domains still return a short list.
34
+ */
35
+ export function niceTicks(domain, count = 5) {
36
+ let [min, max] = domain;
37
+ if (!Number.isFinite(min) || !Number.isFinite(max)) {
38
+ const known = [min, max].find(Number.isFinite);
39
+ return [known ?? 0];
40
+ }
41
+ if (min > max)
42
+ [min, max] = [max, min];
43
+ if (min === max)
44
+ return [min];
45
+ const raw = (max - min) / Math.max(1, count);
46
+ const power = 10 ** Math.floor(Math.log10(raw));
47
+ const step = [1, 2, 5, 10].map((m) => m * power).find((s) => s >= raw) ?? 10 * power;
48
+ // Round to the step's precision so 0.1 + 0.2 style drift never shows.
49
+ const digits = Math.min(20, Math.max(0, -Math.floor(Math.log10(step))));
50
+ const ticks = [];
51
+ for (let v = Math.floor(min / step) * step; ticks.length < 50; v += step) {
52
+ ticks.push(Number(v.toFixed(digits)));
53
+ // Stop at the maximum, or when the step is too small to change v at
54
+ // this magnitude (huge values with a tiny span).
55
+ if (v >= max - step * 1e-9 || v + step === v)
56
+ break;
57
+ }
58
+ return ticks;
59
+ }
60
+ /** SVG path data for a polyline through the points; breaks at non-finite y. */
61
+ export function linePath(points) {
62
+ let d = "";
63
+ let pen = false;
64
+ for (const { x, y } of points) {
65
+ if (!Number.isFinite(y)) {
66
+ pen = false;
67
+ continue;
68
+ }
69
+ d += `${pen ? "L" : "M"}${round(x)} ${round(y)}`;
70
+ pen = true;
71
+ }
72
+ return d;
73
+ }
74
+ /**
75
+ * SVG path data for the area between a line and a baseline y: one closed
76
+ * shape per run of finite values, so a missing value leaves a gap.
77
+ */
78
+ export function areaPath(points, baseline) {
79
+ let d = "";
80
+ let run = [];
81
+ const close = () => {
82
+ if (run.length >= 2) {
83
+ const first = run[0];
84
+ const last = run[run.length - 1];
85
+ d += `${linePath(run)}L${round(last.x)} ${round(baseline)}L${round(first.x)} ${round(baseline)}Z`;
86
+ }
87
+ run = [];
88
+ };
89
+ for (const p of points) {
90
+ if (Number.isFinite(p.y))
91
+ run.push(p);
92
+ else
93
+ close();
94
+ }
95
+ close();
96
+ return d;
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
+ }
125
+ const round = (n) => Math.round(n * 100) / 100;
126
+ /** The CSS colour of a series slot, from the --m-chart-* tokens. */
127
+ export const seriesColour = (slot) => `var(--m-chart-${slot})`;
@@ -0,0 +1,5 @@
1
+ export { Sparkline } from "./sparkline.js";
2
+ export { LineChart, AreaChart, BarChart } from "./xy-chart.js";
3
+ export type { SparklineProps } from "./sparkline.js";
4
+ export type { ChartBaseProps, ChartSeries, ChartX, ChartY, LineChartProps, AreaChartProps, BarChartProps, } from "./xy-chart.js";
5
+ export type { ChartSlot } from "./chart-core.js";
package/dist/charts.js ADDED
@@ -0,0 +1,4 @@
1
+ /* @tonycodes-ui/mortar/charts: charts drawn as SVG with Mortar's tokens, with
2
+ no runtime dependencies. See docs/charts.md. */
3
+ export { Sparkline } from "./sparkline.js";
4
+ export { LineChart, AreaChart, BarChart } from "./xy-chart.js";
@@ -0,0 +1,28 @@
1
+ import { type ChartSlot } from "./chart-core.js";
2
+ export interface SparklineProps {
3
+ /** The values in order, oldest first. Missing values (NaN) break the line. */
4
+ values: readonly number[];
5
+ /** What the values measure, e.g. "Revenue, last 12 months". Read as the start of its summary. */
6
+ label: string;
7
+ /** Formats values in the spoken summary. Defaults to the locale's number format. */
8
+ format?: (value: number) => string;
9
+ /** Series colour slot, 1–8. Default 1. */
10
+ slot?: ChartSlot;
11
+ /** Height in pixels; the width follows the container. Default 32. */
12
+ height?: number;
13
+ /** Mark the latest value with a dot. Default true. */
14
+ showLast?: boolean;
15
+ /** Fill under the line. */
16
+ area?: boolean;
17
+ /** Shade a reference range, such as a target or normal band. */
18
+ band?: {
19
+ min: number;
20
+ max: number;
21
+ };
22
+ id?: string;
23
+ className?: string;
24
+ }
25
+ /** The spoken summary: label, count, range and latest value. */
26
+ export declare function sparklineSummary(values: readonly number[], label: string, format?: (value: number) => string): string;
27
+ /** A small, axis-free trend line for a stat tile, table cell or list row. */
28
+ export declare function Sparkline({ values, label, format, slot, height, showLast, area, band, id, className, }: SparklineProps): import("react").JSX.Element;
@@ -0,0 +1,31 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { componentRoot, cx } from "./internal.js";
3
+ import { areaPath, extent, linearScale, linePath, seriesColour, } from "./chart-core.js";
4
+ const number = new Intl.NumberFormat();
5
+ /** The spoken summary: label, count, range and latest value. */
6
+ export function sparklineSummary(values, label, format = (v) => number.format(v)) {
7
+ const finite = values.filter(Number.isFinite);
8
+ if (!finite.length)
9
+ return `${label}: no data`;
10
+ const [min, max] = extent(finite);
11
+ const last = finite[finite.length - 1];
12
+ return finite.length === 1
13
+ ? `${label}: ${format(last)}`
14
+ : `${label}: ${finite.length} values from ${format(min)} to ${format(max)}, latest ${format(last)}`;
15
+ }
16
+ /** A small, axis-free trend line for a stat tile, table cell or list row. */
17
+ export function Sparkline({ values, label, format, slot = 1, height = 32, showLast = true, area = false, band, id, className, }) {
18
+ const [min, max] = extent(band ? [...values, band.min, band.max] : [...values]);
19
+ // A single value maps through a flat domain to the middle.
20
+ const x = linearScale([0, values.length - 1], [0, 100]);
21
+ const y = linearScale([min, max], [100, 0]);
22
+ const points = values.map((v, i) => ({ x: x(i), y: y(v) }));
23
+ let lastIndex = values.length - 1;
24
+ while (lastIndex >= 0 && !Number.isFinite(values[lastIndex]))
25
+ lastIndex--;
26
+ const last = lastIndex >= 0 ? points[lastIndex] : undefined;
27
+ return (_jsx("span", { id: id, ...componentRoot("Sparkline"), className: cx("m-sparkline", className), role: "img", "aria-label": sparklineSummary(values, label, format), style: {
28
+ height,
29
+ "--m-sparkline-colour": seriesColour(slot),
30
+ }, children: _jsxs("span", { className: "m-sparkline-plot", children: [_jsxs("svg", { viewBox: "0 0 100 100", preserveAspectRatio: "none", "aria-hidden": "true", focusable: "false", children: [band && (_jsx("rect", { className: "m-sparkline-band", x: "0", width: "100", y: Math.min(y(band.min), y(band.max)), height: Math.abs(y(band.min) - y(band.max)) })), area && (_jsx("path", { className: "m-sparkline-area", d: areaPath(points, 100) })), _jsx("path", { className: "m-sparkline-line", d: linePath(points), vectorEffect: "non-scaling-stroke" })] }), showLast && last && (_jsx("span", { className: "m-sparkline-last", style: { left: `${last.x}%`, top: `${last.y}%` }, "aria-hidden": "true" }))] }) }));
31
+ }
@@ -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 {};