@tonycodes-ui/mortar 0.28.1 → 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.
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.
@@ -0,0 +1,155 @@
1
+ # DataGrid
2
+
3
+ `DataGrid` is the interactive table for large or server-driven data: multi-column sort, column filters, search, selection across pages, paging, hidden and pinned columns, and row virtualization for tens of thousands of rows. It ships from its own entry point, `@tonycodes-ui/mortar/data-grid`, and renders the same markup and styles as `DataTable`, so the two look the same side by side.
4
+
5
+ ## DataGrid or DataTable
6
+
7
+ | Use | When |
8
+ | ----------- | ------------------------------------------------------------------------------------------------------------------------- |
9
+ | `DataTable` | A few hundred rows or fewer, single-column sort, your own toolbar. It has no extra dependencies. |
10
+ | `DataGrid` | Thousands of rows, data the server sorts and pages, or people need filters, search, multi-sort, hidden or pinned columns. |
11
+
12
+ Moving from `DataTable` is mostly a rename: `DataGridColumn` takes every `DataTableColumn` field, and `caption`, `rows`, `rowLabel`, `selectedIds`, `onSelectionChange`, `bulkActions`, `rowHref`, `empty`, `loading`, `error`, `density` and `striped` work the same way. `sort` becomes a list of sort levels.
13
+
14
+ ## Install
15
+
16
+ The grid's engine, [TanStack Table](https://tanstack.com/table) and [TanStack Virtual](https://tanstack.com/virtual), are optional peer dependencies. Install them only in apps that import the grid:
17
+
18
+ ```sh
19
+ npm install @tanstack/react-table @tanstack/react-virtual
20
+ ```
21
+
22
+ The grid needs both packages whenever it is imported, even when it isn't virtualized. Mortar's stylesheet already includes the grid's styles, so there is nothing else to import.
23
+
24
+ In server mode, always pass `rowCount`. Without it the grid counts only the rows it was given, so paging shows a single page.
25
+
26
+ ## Client mode
27
+
28
+ In client mode (the default) the grid sorts, filters, searches and pages every row in the browser. Pass all the rows.
29
+
30
+ ```tsx
31
+ import { Badge, Button } from "@tonycodes-ui/mortar";
32
+ import { DataGrid, type DataGridColumn } from "@tonycodes-ui/mortar/data-grid";
33
+
34
+ const columns: DataGridColumn<Invoice>[] = [
35
+ {
36
+ key: "number",
37
+ label: "Invoice",
38
+ render: (r) => r.number,
39
+ sortable: true,
40
+ pin: "start",
41
+ },
42
+ {
43
+ key: "customer",
44
+ label: "Customer",
45
+ render: (r) => r.customer,
46
+ sortable: true,
47
+ filter: "text",
48
+ },
49
+ {
50
+ key: "amount",
51
+ label: "Amount",
52
+ render: (r) => money.format(r.amount),
53
+ align: "end",
54
+ sortable: true,
55
+ },
56
+ {
57
+ key: "status",
58
+ label: "Status",
59
+ render: (r) => <Badge tone={tone[r.status]}>{r.status}</Badge>,
60
+ filter: { options: statusOptions },
61
+ pin: "end",
62
+ },
63
+ ];
64
+
65
+ <DataGrid
66
+ caption="Invoices"
67
+ rows={invoices}
68
+ columns={columns}
69
+ rowLabel={(r) => r.number}
70
+ searchable
71
+ virtualize
72
+ selectedIds={selected}
73
+ onSelectionChange={setSelected}
74
+ bulkActions={<Button variant="secondary">Mark as paid</Button>}
75
+ noun="invoices"
76
+ />;
77
+ ```
78
+
79
+ `render` controls what a cell shows. Sorting, filters and search use the raw value instead: `sortValue(row)` for sorting and `filterValue(row)` for filters and search, both defaulting to `row[key]`. Give dates and amounts a `sortValue` that returns the `Date` or number, and a `filterValue` that returns the text people will type.
80
+
81
+ ## Server mode
82
+
83
+ With `mode="server"` the grid never sorts, filters or pages rows itself. It reports what people asked for, and you fetch the matching page and its total.
84
+
85
+ ```tsx
86
+ const [sort, setSort] = useState<TableSort[]>([
87
+ { key: "issued", direction: "descending" },
88
+ ]);
89
+ const [filters, setFilters] = useState<DataGridFilters>({});
90
+ const [search, setSearch] = useState("");
91
+ const [pagination, setPagination] = useState({ page: 1, pageSize: 50 });
92
+ const { data, isLoading, error } = useInvoices({
93
+ sort,
94
+ filters,
95
+ search,
96
+ pagination,
97
+ });
98
+
99
+ <DataGrid
100
+ caption="Invoices"
101
+ mode="server"
102
+ rows={data?.rows ?? []}
103
+ rowCount={data?.total ?? 0}
104
+ columns={columns}
105
+ rowLabel={(r) => r.number}
106
+ sort={sort}
107
+ onSortChange={setSort}
108
+ filters={filters}
109
+ onFiltersChange={setFilters}
110
+ searchable
111
+ search={search}
112
+ onSearchChange={setSearch}
113
+ pagination={pagination}
114
+ onPaginationChange={setPagination}
115
+ loading={isLoading}
116
+ error={error?.message}
117
+ />;
118
+ ```
119
+
120
+ Put the state in your request key, so a change fetches again. Filtering or searching returns to page 1.
121
+
122
+ ## State
123
+
124
+ Every piece of state is controlled when you pass its value and its `on…Change` callback, and kept by the grid when you pass only a `default…` value (or nothing):
125
+
126
+ | State | Controlled | Uncontrolled |
127
+ | -------------- | ---------------------------------------- | ---------------------- |
128
+ | Sort levels | `sort`, `onSortChange` | `defaultSort` |
129
+ | Column filters | `filters`, `onFiltersChange` | `defaultFilters` |
130
+ | Search | `search`, `onSearchChange` | `defaultSearch` |
131
+ | Hidden columns | `hiddenColumns`, `onHiddenColumnsChange` | `defaultHiddenColumns` |
132
+ | Paging | `pagination`, `onPaginationChange` | `defaultPagination` |
133
+ | Selection | `selectedIds`, `onSelectionChange` | none |
134
+
135
+ Hidden columns and sort levels are plain arrays, so they are easy to save per user.
136
+
137
+ ## Behaviour
138
+
139
+ - **Sorting.** Click a header to sort; click again to reverse, and a third time to remove the sort. Shift-click adds the column as another level; numbered badges show the order. Empty values sort last in both directions, as in `DataTable`.
140
+ - **Filters and search.** A column with `filter: "text"` gets a text box that matches part of the value, ignoring case; `filter: { options }` gets a choice that matches exactly. `searchable` adds a field that searches every column's filter value. The status region announces the number of matching rows, and when nothing matches the grid offers to clear the filters.
141
+ - **Selection.** "Select all" selects every matching row in client mode and the loaded page in server mode, and keeps selections made elsewhere. Selected ids may include rows that are not loaded.
142
+ - **Paging or virtualization.** Pass `pagination` to page rows, or `virtualize` to render only the rows in view. Virtualization needs a fixed height: `maxHeight`, which defaults to 32rem when virtualizing. Without either, every row renders.
143
+ - **Columns.** People can hide any column but the first from the Columns menu; set `hideable: false` to keep one. `pin: "start"` or `pin: "end"` keeps a column in view while the grid scrolls sideways. `priority` hides secondary columns on narrow grids, as in `DataTable`.
144
+
145
+ ## Accessibility
146
+
147
+ The grid is a semantic table with a caption, `scope` on headers and `aria-sort` on the sorted column. A virtualized grid sets `aria-rowcount` and each row's `aria-rowindex`, so screen readers know where they are in the full set. Every row checkbox is named from `rowLabel`. Check keyboard use and focus in your own toolbar content and bulk actions.
148
+
149
+ ## Performance
150
+
151
+ With 100,000 client-side rows in the playground, sorting takes about 250ms, searching about 300ms, and scrolling stays at one frame (about 17ms) with fewer than 30 rows in the page. `tests/browser/data-grid-performance.spec.mjs` holds the budget. Keep `columns` stable (define them outside the component or memoise them): a new array every render rebuilds the grid's column definitions.
152
+
153
+ ## Not yet
154
+
155
+ Column resizing and reordering, grouping with totals, expandable detail rows and inline editing are planned and not in this version.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonycodes-ui/mortar",
3
- "version": "0.28.1",
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",
@@ -53,6 +53,14 @@
53
53
  "./email": {
54
54
  "types": "./dist/email.d.ts",
55
55
  "import": "./dist/email.js"
56
+ },
57
+ "./data-grid": {
58
+ "types": "./dist/data-grid.d.ts",
59
+ "import": "./dist/data-grid.js"
60
+ },
61
+ "./charts": {
62
+ "types": "./dist/charts.d.ts",
63
+ "import": "./dist/charts.js"
56
64
  }
57
65
  },
58
66
  "sideEffects": [
@@ -78,11 +86,19 @@
78
86
  "react": "^19.0.0",
79
87
  "react-dom": "^19.0.0",
80
88
  "tailwindcss": "^4.0.0",
81
- "@react-email/components": "^1.0.12"
89
+ "@react-email/components": "^1.0.12",
90
+ "@tanstack/react-table": "^9.3.1",
91
+ "@tanstack/react-virtual": "^3.14.28"
82
92
  },
83
93
  "peerDependenciesMeta": {
84
94
  "@react-email/components": {
85
95
  "optional": true
96
+ },
97
+ "@tanstack/react-table": {
98
+ "optional": true
99
+ },
100
+ "@tanstack/react-virtual": {
101
+ "optional": true
86
102
  }
87
103
  },
88
104
  "dependencies": {
@@ -102,7 +118,9 @@
102
118
  "@playwright/test": "^1.63.0",
103
119
  "@axe-core/playwright": "^4.13.0",
104
120
  "@modelcontextprotocol/sdk": "^1.32.1",
105
- "@react-email/components": "^1.0.12"
121
+ "@react-email/components": "^1.0.12",
122
+ "@tanstack/react-table": "^9.3.1",
123
+ "@tanstack/react-virtual": "^3.14.28"
106
124
  },
107
125
  "license": "MIT",
108
126
  "publishConfig": {
@@ -14,7 +14,7 @@ Mortar is an MIT React 19 + Tailwind 4 UI kit. Its agent tooling ships in the pa
14
14
  3. **Compose** following the defaults below.
15
15
  4. **Emails.** Build transactional emails from `@tonycodes-ui/mortar/email` (`get_guide email`), never from the app components.
16
16
  5. **Native apps.** For iPhone, iPad and Android, use Mortar for SwiftUI and Mortar for Jetpack Compose (`get_guide native`): each component's contract names its native equivalent. Build what they don't have from the platform's own controls, styled with `MortarTokens`.
17
- 6. **Audit.** Run `audit_app` on the application (`npx mortar audit`), fix every error and review the warnings, then rerun it with the app's build and typecheck.
17
+ 6. **Audit.** Run `audit_app` on the application (`npx mortar audit`), fix every error and review the warnings, then rerun it with the app's build and typecheck. With the app running, pass its page URLs as `render` (`npx mortar audit . --render <url>`) to check the rendered pages too.
18
18
  7. **Verify** in a browser and report the actual results.
19
19
 
20
20
  ## Defaults
@@ -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,53 +706,34 @@ 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
  }))}
709
719
  />
710
720
  );
711
721
  }
712
- export type SortDirection = "ascending" | "descending";
713
- export interface TableSort {
714
- key: string;
715
- direction: SortDirection;
716
- }
717
- export interface DataTableColumn<T> {
718
- key: string;
719
- label: string;
720
- render: (row: T) => ReactNode;
721
- /** `end` aligns numbers and amounts to the trailing edge. */
722
- align?: "start" | "end";
723
- /** Enable header sorting. Supply sortValue unless row[key] is a string, number or Date. */
724
- sortable?: boolean;
725
- sortValue?: (row: T) => string | number | Date | null | undefined;
726
- /** CSS width, e.g. "12rem" or "30%". */
727
- width?: string;
728
- /** Clip long values to one line with an ellipsis. */
729
- truncate?: boolean;
730
- /**
731
- * How long the column stays as the table narrows (its own width, not the
732
- * screen's): `medium` hides below 480px, `low` below 768px. The first
733
- * column always shows. Hidden columns leave the accessibility tree too, so
734
- * keep what people need in visible columns or on the detail page.
735
- */
736
- priority?: "high" | "medium" | "low";
737
- /**
738
- * `end` pins the column to the trailing edge while the table scrolls
739
- * sideways, so a row-actions or status column stays reachable.
740
- */
741
- pin?: "end";
742
- }
743
- /** Responsive attributes shared by a column's `col`, header and cells. */
744
- function columnLayout<T>(col: DataTableColumn<T>, index: number) {
745
- return {
746
- "data-priority":
747
- index > 0 && col.priority && col.priority !== "high"
748
- ? col.priority
749
- : undefined,
750
- "data-pin": col.pin,
751
- };
752
- }
722
+ export type {
723
+ SortDirection,
724
+ TableSort,
725
+ DataTableColumn,
726
+ } from "./table-core.js";
727
+ import {
728
+ columnAlign,
729
+ columnLayout,
730
+ groupRows,
731
+ SelectAll,
732
+ sortRows,
733
+ TableGroupRow,
734
+ type DataTableColumn,
735
+ type TableSort,
736
+ } from "./table-core.js";
753
737
  export interface DataTableProps<T extends { id: string }> {
754
738
  caption: string;
755
739
  columns: DataTableColumn<T>[];
@@ -784,79 +768,6 @@ export interface DataTableProps<T extends { id: string }> {
784
768
  id?: string;
785
769
  className?: string;
786
770
  }
787
- const collator = new Intl.Collator(undefined, {
788
- numeric: true,
789
- sensitivity: "base",
790
- });
791
- const isEmpty = (v: unknown) => v === null || v === undefined || v === "";
792
- function compareValues(a: unknown, b: unknown) {
793
- if (isEmpty(a) || isEmpty(b))
794
- return isEmpty(a) === isEmpty(b) ? 0 : isEmpty(a) ? 1 : -1;
795
- if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
796
- if (typeof a === "number" && typeof b === "number") return a - b;
797
- return collator.compare(String(a), String(b));
798
- }
799
- /** Stable sort; empty values always sort last regardless of direction. */
800
- export function sortRows<T>(
801
- rows: T[],
802
- column: Pick<DataTableColumn<T>, "key" | "sortValue">,
803
- direction: SortDirection,
804
- ) {
805
- const value =
806
- column.sortValue ||
807
- ((row: T) => (row as Record<string, unknown>)[column.key] as string);
808
- const sign = direction === "ascending" ? 1 : -1;
809
- return rows
810
- .map((row, index) => ({ row, index, v: value(row) }))
811
- .sort(
812
- (a, b) =>
813
- // Empty values sort last in both directions, so only real values flip.
814
- (isEmpty(a.v) || isEmpty(b.v) ? 1 : sign) * compareValues(a.v, b.v) ||
815
- a.index - b.index,
816
- )
817
- .map((entry) => entry.row);
818
- }
819
- function SelectAll({
820
- checked,
821
- partial,
822
- onChange,
823
- }: {
824
- checked: boolean;
825
- partial: boolean;
826
- onChange: () => void;
827
- }) {
828
- const ref = useRef<HTMLInputElement>(null);
829
- useEffect(() => {
830
- if (ref.current) ref.current.indeterminate = partial;
831
- }, [partial]);
832
- return (
833
- <input
834
- ref={ref}
835
- type="checkbox"
836
- aria-label="Select all rows"
837
- checked={checked}
838
- onChange={onChange}
839
- />
840
- );
841
- }
842
- /** Buckets ordered rows by group; groups keep their first-appearance order in the unsorted rows. */
843
- function groupRows<T>(rows: T[], ordered: T[], groupBy: (row: T) => string) {
844
- const groups = new Map<string, T[]>(rows.map((row) => [groupBy(row), []]));
845
- ordered.forEach((row) => groups.get(groupBy(row))!.push(row));
846
- return [...groups];
847
- }
848
- /** Full-width header row that labels the rows of its tbody. */
849
- function TableGroupRow({ label, span }: { label: string; span: number }) {
850
- return (
851
- <tr className="m-table-group">
852
- <th colSpan={span} scope="rowgroup">
853
- {label}
854
- </th>
855
- </tr>
856
- );
857
- }
858
- const columnAlign = (align?: "start" | "end") =>
859
- align === "end" ? "end" : undefined;
860
771
  export function DataTable<T extends { id: string }>({
861
772
  caption,
862
773
  columns,
@@ -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";
@@ -0,0 +1,13 @@
1
+ /* @tonycodes-ui/mortar/data-grid: DataGrid for large and server-driven data,
2
+ built on the optional peer dependencies @tanstack/react-table and
3
+ @tanstack/react-virtual. Install both to use this entry point. */
4
+
5
+ export { DataGrid } from "./grid.js";
6
+ export type {
7
+ DataGridColumn,
8
+ DataGridFilters,
9
+ DataGridPagination,
10
+ DataGridProps,
11
+ SortDirection,
12
+ TableSort,
13
+ } from "./grid.js";