@tonycodes-ui/mortar 0.29.0 → 0.30.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,30 @@
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
+ /** A categorical series slot. There are eight and they are never reused: a
27
+ ninth series belongs in "Other" or in its own chart. */
28
+ export type ChartSlot = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
29
+ /** The CSS colour of a series slot, from the --m-chart-* tokens. */
30
+ export declare const seriesColour: (slot: ChartSlot) => string;
@@ -0,0 +1,100 @@
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
+ const round = (n) => Math.round(n * 100) / 100;
99
+ /** The CSS colour of a series slot, from the --m-chart-* tokens. */
100
+ export const seriesColour = (slot) => `var(--m-chart-${slot})`;
@@ -0,0 +1,3 @@
1
+ export { Sparkline } from "./sparkline.js";
2
+ export type { SparklineProps } from "./sparkline.js";
3
+ export type { ChartSlot } from "./chart-core.js";
package/dist/charts.js ADDED
@@ -0,0 +1,3 @@
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";
@@ -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
+ }
package/docs/charts.md ADDED
@@ -0,0 +1,68 @@
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`; line, area and bar charts and a meter are 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
+ ## Accessibility
42
+
43
+ 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
+
45
+ ## Colour
46
+
47
+ Series use eight colour tokens, `--m-chart-1` to `--m-chart-8`, in a fixed order:
48
+
49
+ | Slot | Hue | Light | Dark |
50
+ | ---- | ------- | --------- | --------- |
51
+ | 1 | blue | `#2a78d6` | `#3987e5` |
52
+ | 2 | orange | `#eb6834` | `#d95926` |
53
+ | 3 | aqua | `#1baf7a` | `#199e70` |
54
+ | 4 | yellow | `#eda100` | `#c98500` |
55
+ | 5 | magenta | `#e87ba4` | `#d55181` |
56
+ | 6 | green | `#008300` | `#0ca30c` |
57
+ | 7 | violet | `#6250d6` | `#9085e9` |
58
+ | 8 | red | `#e34948` | `#e66767` |
59
+
60
+ 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.
61
+
62
+ Rules that keep charts readable:
63
+
64
+ - Give a series the same slot everywhere it appears, and keep it when other series are hidden.
65
+ - There are eight slots and they are never reused. A ninth series belongs in "Other" or in a separate chart.
66
+ - 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.
67
+ - Text uses the text tokens, never a series colour.
68
+ - 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.29.0",
3
+ "version": "0.30.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": [
@@ -579,7 +579,8 @@
579
579
  letter-spacing: var(--m-tracking-heading);
580
580
  font-variant-numeric: tabular-nums;
581
581
  }
582
- .m-metrics span {
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;
@@ -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
  }))}
@@ -0,0 +1,113 @@
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
+
4
+ export type Extent = readonly [number, number];
5
+
6
+ /** Smallest and largest finite value; [0, 0] when there are none. */
7
+ export function extent(values: readonly number[]): Extent {
8
+ let min = Infinity;
9
+ let max = -Infinity;
10
+ for (const v of values)
11
+ if (Number.isFinite(v)) {
12
+ if (v < min) min = v;
13
+ if (v > max) max = v;
14
+ }
15
+ return min === Infinity ? [0, 0] : [min, max];
16
+ }
17
+
18
+ /**
19
+ * Maps a domain onto a range linearly. A flat domain maps to the range's
20
+ * middle. A missing value (NaN) stays missing, so lines keep their gaps.
21
+ */
22
+ export function linearScale(domain: Extent, range: Extent) {
23
+ const [d0, d1] = domain;
24
+ const [r0, r1] = range;
25
+ const span = d1 - d0;
26
+ return (value: number) =>
27
+ !Number.isFinite(value)
28
+ ? Number.NaN
29
+ : span === 0
30
+ ? (r0 + r1) / 2
31
+ : r0 + ((value - d0) / span) * (r1 - r0);
32
+ }
33
+
34
+ /**
35
+ * "Nice" tick values from the step at or below the minimum to the first step
36
+ * at or above the maximum, so the top gridline is never below the data.
37
+ * Inverted, non-finite and degenerate domains still return a short list.
38
+ */
39
+ export function niceTicks(domain: Extent, count = 5): number[] {
40
+ let [min, max] = domain;
41
+ if (!Number.isFinite(min) || !Number.isFinite(max)) {
42
+ const known = [min, max].find(Number.isFinite);
43
+ return [known ?? 0];
44
+ }
45
+ if (min > max) [min, max] = [max, min];
46
+ if (min === max) return [min];
47
+ const raw = (max - min) / Math.max(1, count);
48
+ const power = 10 ** Math.floor(Math.log10(raw));
49
+ const step =
50
+ [1, 2, 5, 10].map((m) => m * power).find((s) => s >= raw) ?? 10 * power;
51
+ // Round to the step's precision so 0.1 + 0.2 style drift never shows.
52
+ const digits = Math.min(20, Math.max(0, -Math.floor(Math.log10(step))));
53
+ const ticks: number[] = [];
54
+ for (let v = Math.floor(min / step) * step; ticks.length < 50; v += step) {
55
+ ticks.push(Number(v.toFixed(digits)));
56
+ // Stop at the maximum, or when the step is too small to change v at
57
+ // this magnitude (huge values with a tiny span).
58
+ if (v >= max - step * 1e-9 || v + step === v) break;
59
+ }
60
+ return ticks;
61
+ }
62
+
63
+ export interface Point {
64
+ x: number;
65
+ y: number;
66
+ }
67
+
68
+ /** SVG path data for a polyline through the points; breaks at non-finite y. */
69
+ export function linePath(points: readonly Point[]): string {
70
+ let d = "";
71
+ let pen = false;
72
+ for (const { x, y } of points) {
73
+ if (!Number.isFinite(y)) {
74
+ pen = false;
75
+ continue;
76
+ }
77
+ d += `${pen ? "L" : "M"}${round(x)} ${round(y)}`;
78
+ pen = true;
79
+ }
80
+ return d;
81
+ }
82
+
83
+ /**
84
+ * SVG path data for the area between a line and a baseline y: one closed
85
+ * shape per run of finite values, so a missing value leaves a gap.
86
+ */
87
+ export function areaPath(points: readonly Point[], baseline: number): string {
88
+ let d = "";
89
+ let run: Point[] = [];
90
+ const close = () => {
91
+ if (run.length >= 2) {
92
+ const first = run[0];
93
+ const last = run[run.length - 1];
94
+ d += `${linePath(run)}L${round(last.x)} ${round(baseline)}L${round(first.x)} ${round(baseline)}Z`;
95
+ }
96
+ run = [];
97
+ };
98
+ for (const p of points) {
99
+ if (Number.isFinite(p.y)) run.push(p);
100
+ else close();
101
+ }
102
+ close();
103
+ return d;
104
+ }
105
+
106
+ const round = (n: number) => Math.round(n * 100) / 100;
107
+
108
+ /** A categorical series slot. There are eight and they are never reused: a
109
+ ninth series belongs in "Other" or in its own chart. */
110
+ export type ChartSlot = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
111
+
112
+ /** The CSS colour of a series slot, from the --m-chart-* tokens. */
113
+ export const seriesColour = (slot: ChartSlot) => `var(--m-chart-${slot})`;
package/src/charts.css ADDED
@@ -0,0 +1,58 @@
1
+ /* Charts: Sparkline. Series colours come from the --m-chart-* tokens; text
2
+ always uses the text tokens, never a series colour. Every rule sits in
3
+ @layer components, like the other component families. */
4
+ @layer components {
5
+ /* == Sparkline == */
6
+ .m-sparkline {
7
+ display: inline-block;
8
+ width: 100%;
9
+ min-width: 48px;
10
+ /* Room for the 8px dot and its 2px ring at the top, end and bottom. */
11
+ padding: 6px 6px 6px 0;
12
+ vertical-align: middle;
13
+ }
14
+ .m-sparkline-plot {
15
+ position: relative;
16
+ display: block;
17
+ height: 100%;
18
+ }
19
+ .m-sparkline svg {
20
+ display: block;
21
+ width: 100%;
22
+ height: 100%;
23
+ overflow: visible;
24
+ }
25
+ .m-sparkline-line {
26
+ fill: none;
27
+ stroke: var(--m-sparkline-colour);
28
+ stroke-width: 2px;
29
+ stroke-linecap: round;
30
+ stroke-linejoin: round;
31
+ }
32
+ .m-sparkline-area {
33
+ fill: var(--m-sparkline-colour);
34
+ fill-opacity: 0.12;
35
+ }
36
+ .m-sparkline-band {
37
+ fill: var(--m-sunken);
38
+ }
39
+ /* The dot sits in HTML so it stays round when the SVG stretches. A surface
40
+ ring separates it from the line. */
41
+ .m-sparkline-last {
42
+ position: absolute;
43
+ width: 8px;
44
+ height: 8px;
45
+ margin: -4px 0 0 -4px;
46
+ border-radius: var(--m-radius-full);
47
+ background: var(--m-sparkline-colour);
48
+ box-shadow: 0 0 0 2px var(--m-surface);
49
+ }
50
+ @media (forced-colors: active) {
51
+ .m-sparkline-line {
52
+ stroke: CanvasText;
53
+ }
54
+ .m-sparkline-last {
55
+ background: CanvasText;
56
+ }
57
+ }
58
+ }
package/src/charts.ts ADDED
@@ -0,0 +1,6 @@
1
+ /* @tonycodes-ui/mortar/charts: charts drawn as SVG with Mortar's tokens, with
2
+ no runtime dependencies. See docs/charts.md. */
3
+
4
+ export { Sparkline } from "./sparkline.js";
5
+ export type { SparklineProps } from "./sparkline.js";
6
+ export type { ChartSlot } from "./chart-core.js";