@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.
@@ -187,43 +187,16 @@ 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";
193
195
  className?: string;
194
196
  }
195
197
  export declare function MetricGroup({ label, items, variant, className, }: MetricGroupProps): import("react").JSX.Element;
196
- export type SortDirection = "ascending" | "descending";
197
- export interface TableSort {
198
- key: string;
199
- direction: SortDirection;
200
- }
201
- export interface DataTableColumn<T> {
202
- key: string;
203
- label: string;
204
- render: (row: T) => ReactNode;
205
- /** `end` aligns numbers and amounts to the trailing edge. */
206
- align?: "start" | "end";
207
- /** Enable header sorting. Supply sortValue unless row[key] is a string, number or Date. */
208
- sortable?: boolean;
209
- sortValue?: (row: T) => string | number | Date | null | undefined;
210
- /** CSS width, e.g. "12rem" or "30%". */
211
- width?: string;
212
- /** Clip long values to one line with an ellipsis. */
213
- truncate?: boolean;
214
- /**
215
- * How long the column stays as the table narrows (its own width, not the
216
- * screen's): `medium` hides below 480px, `low` below 768px. The first
217
- * column always shows. Hidden columns leave the accessibility tree too, so
218
- * keep what people need in visible columns or on the detail page.
219
- */
220
- priority?: "high" | "medium" | "low";
221
- /**
222
- * `end` pins the column to the trailing edge while the table scrolls
223
- * sideways, so a row-actions or status column stays reachable.
224
- */
225
- pin?: "end";
226
- }
198
+ export type { SortDirection, TableSort, DataTableColumn, } from "./table-core.js";
199
+ import { type DataTableColumn, type TableSort } from "./table-core.js";
227
200
  export interface DataTableProps<T extends {
228
201
  id: string;
229
202
  }> {
@@ -264,8 +237,6 @@ export interface DataTableProps<T extends {
264
237
  id?: string;
265
238
  className?: string;
266
239
  }
267
- /** Stable sort; empty values always sort last regardless of direction. */
268
- export declare function sortRows<T>(rows: T[], column: Pick<DataTableColumn<T>, "key" | "sortValue">, direction: SortDirection): T[];
269
240
  export declare function DataTable<T extends {
270
241
  id: string;
271
242
  }>({ caption, columns, rows, selectedIds, onSelectionChange, rowLabel, rowHref, defaultSort, sort: controlledSort, onSortChange, groupBy, maxHeight, density, striped, toolbar, bulkActions, footer, empty, headingLevel, loading, error, id, className, }: DataTableProps<T>): import("react").JSX.Element;
@@ -1,10 +1,11 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { KitLink } from "./navigation.js";
3
- import { useId, useRef, useEffect, useState, } from "react";
3
+ import { useId, useState, } from "react";
4
4
  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,64 +85,10 @@ 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
- /** Responsive attributes shared by a column's `col`, header and cells. */
91
- function columnLayout(col, index) {
92
- return {
93
- "data-priority": index > 0 && col.priority && col.priority !== "high"
94
- ? col.priority
95
- : undefined,
96
- "data-pin": col.pin,
97
- };
98
- }
99
- const collator = new Intl.Collator(undefined, {
100
- numeric: true,
101
- sensitivity: "base",
102
- });
103
- const isEmpty = (v) => v === null || v === undefined || v === "";
104
- function compareValues(a, b) {
105
- if (isEmpty(a) || isEmpty(b))
106
- return isEmpty(a) === isEmpty(b) ? 0 : isEmpty(a) ? 1 : -1;
107
- if (a instanceof Date && b instanceof Date)
108
- return a.getTime() - b.getTime();
109
- if (typeof a === "number" && typeof b === "number")
110
- return a - b;
111
- return collator.compare(String(a), String(b));
112
- }
113
- /** Stable sort; empty values always sort last regardless of direction. */
114
- export function sortRows(rows, column, direction) {
115
- const value = column.sortValue ||
116
- ((row) => row[column.key]);
117
- const sign = direction === "ascending" ? 1 : -1;
118
- return rows
119
- .map((row, index) => ({ row, index, v: value(row) }))
120
- .sort((a, b) =>
121
- // Empty values sort last in both directions, so only real values flip.
122
- (isEmpty(a.v) || isEmpty(b.v) ? 1 : sign) * compareValues(a.v, b.v) ||
123
- a.index - b.index)
124
- .map((entry) => entry.row);
125
- }
126
- function SelectAll({ checked, partial, onChange, }) {
127
- const ref = useRef(null);
128
- useEffect(() => {
129
- if (ref.current)
130
- ref.current.indeterminate = partial;
131
- }, [partial]);
132
- return (_jsx("input", { ref: ref, type: "checkbox", "aria-label": "Select all rows", checked: checked, onChange: onChange }));
133
- }
134
- /** Buckets ordered rows by group; groups keep their first-appearance order in the unsorted rows. */
135
- function groupRows(rows, ordered, groupBy) {
136
- const groups = new Map(rows.map((row) => [groupBy(row), []]));
137
- ordered.forEach((row) => groups.get(groupBy(row)).push(row));
138
- return [...groups];
139
- }
140
- /** Full-width header row that labels the rows of its tbody. */
141
- function TableGroupRow({ label, span }) {
142
- return (_jsx("tr", { className: "m-table-group", children: _jsx("th", { colSpan: span, scope: "rowgroup", children: label }) }));
143
- }
144
- const columnAlign = (align) => align === "end" ? "end" : undefined;
91
+ import { columnAlign, columnLayout, groupRows, SelectAll, sortRows, TableGroupRow, } from "./table-core.js";
145
92
  export function DataTable({ caption, columns, rows, selectedIds = [], onSelectionChange, rowLabel, rowHref, defaultSort, sort: controlledSort, onSortChange, groupBy, maxHeight, density = "default", striped = false, toolbar, bulkActions, footer, empty = {
146
93
  title: "No records",
147
94
  description: "Records will appear here when they are available.",
@@ -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,2 @@
1
+ export { DataGrid } from "./grid.js";
2
+ export type { DataGridColumn, DataGridFilters, DataGridPagination, DataGridProps, SortDirection, TableSort, } from "./grid.js";
@@ -0,0 +1,4 @@
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
+ export { DataGrid } from "./grid.js";
package/dist/grid.d.ts ADDED
@@ -0,0 +1,102 @@
1
+ import { type ReactNode } from "react";
2
+ import type { HeadingLevel } from "./heading.js";
3
+ import { type DataTableColumn, type SortDirection, type TableSort } from "./table-core.js";
4
+ export interface DataGridColumn<T> extends Omit<DataTableColumn<T>, "pin"> {
5
+ /** Keep the column in view while the grid scrolls sideways. */
6
+ pin?: "start" | "end";
7
+ /**
8
+ * Adds a filter control to the toolbar. `text` matches part of the value,
9
+ * ignoring case; `options` offers an exact-match choice.
10
+ */
11
+ filter?: "text" | {
12
+ options: {
13
+ value: string;
14
+ label: string;
15
+ }[];
16
+ };
17
+ /** The value filters and search compare. Defaults to sortValue, then row[key]. */
18
+ filterValue?: (row: T) => string | number | null | undefined;
19
+ /** Whether people can hide the column from the Columns menu. Default true; the first column always shows. */
20
+ hideable?: boolean;
21
+ }
22
+ /** Column key to filter value. A missing or empty value means no filter. */
23
+ export type DataGridFilters = Record<string, string>;
24
+ export interface DataGridPagination {
25
+ /** One-based page number. */
26
+ page: number;
27
+ pageSize: number;
28
+ }
29
+ export interface DataGridProps<T extends {
30
+ id: string;
31
+ }> {
32
+ caption: string;
33
+ columns: DataGridColumn<T>[];
34
+ /** Every row in client mode; the current page in server mode. */
35
+ rows: T[];
36
+ rowLabel: (row: T) => string;
37
+ /**
38
+ * `client` sorts, filters, searches and pages rows in the browser. `server`
39
+ * only reports state changes: pass the matching page of rows and rowCount.
40
+ */
41
+ mode?: "client" | "server";
42
+ /** Total matching rows. Required in server mode. */
43
+ rowCount?: number;
44
+ /** Controlled sort levels, the first sorting first. Shift-click a header to add a level. */
45
+ sort?: TableSort[];
46
+ defaultSort?: TableSort[];
47
+ onSortChange?: (sort: TableSort[]) => void;
48
+ filters?: DataGridFilters;
49
+ defaultFilters?: DataGridFilters;
50
+ onFiltersChange?: (filters: DataGridFilters) => void;
51
+ /** Show a search field that matches any column's filter value. */
52
+ searchable?: boolean;
53
+ /** Controlled search text. */
54
+ search?: string;
55
+ defaultSearch?: string;
56
+ onSearchChange?: (search: string) => void;
57
+ /** Selected row ids, which may include rows that are not loaded. */
58
+ selectedIds?: string[];
59
+ onSelectionChange?: (ids: string[]) => void;
60
+ /** Keys of hidden columns. */
61
+ hiddenColumns?: string[];
62
+ defaultHiddenColumns?: string[];
63
+ onHiddenColumnsChange?: (keys: string[]) => void;
64
+ /** Pages rows when set; without it every row renders (pair large sets with virtualize). */
65
+ pagination?: DataGridPagination;
66
+ defaultPagination?: DataGridPagination;
67
+ onPaginationChange?: (pagination: DataGridPagination) => void;
68
+ /** Render only the rows in view. Needs maxHeight (default 32rem when virtualizing). */
69
+ virtualize?: boolean;
70
+ /** Row height in pixels used for virtualization until a row is measured. Default 44. */
71
+ estimateRowHeight?: number;
72
+ /** Link each row's first cell to a detail page. */
73
+ rowHref?: (row: T) => string | undefined;
74
+ maxHeight?: string;
75
+ density?: "default" | "compact";
76
+ striped?: boolean;
77
+ /** Extra toolbar content, after the built-in search and filters. */
78
+ toolbar?: ReactNode;
79
+ bulkActions?: ReactNode;
80
+ footer?: ReactNode;
81
+ empty?: {
82
+ title: string;
83
+ description?: string;
84
+ action?: ReactNode;
85
+ };
86
+ /** Shown when rows exist but search or filters match none. */
87
+ noResults?: {
88
+ title: string;
89
+ description?: string;
90
+ };
91
+ headingLevel?: HeadingLevel;
92
+ loading?: boolean;
93
+ error?: string;
94
+ /** Plural noun for counts, e.g. "invoices". Default "rows". */
95
+ noun?: string;
96
+ id?: string;
97
+ className?: string;
98
+ }
99
+ export declare function DataGrid<T extends {
100
+ id: string;
101
+ }>({ caption, columns, rows, rowLabel, mode, rowCount, sort: sortProp, defaultSort, onSortChange, filters: filtersProp, defaultFilters, onFiltersChange, searchable, search: searchProp, defaultSearch, onSearchChange, selectedIds: selectedIdsProp, onSelectionChange, hiddenColumns: hiddenProp, defaultHiddenColumns, onHiddenColumnsChange, pagination: paginationProp, defaultPagination, onPaginationChange, virtualize, estimateRowHeight, rowHref, maxHeight, density, striped, toolbar, bulkActions, footer, empty, noResults, headingLevel, loading, error, noun, id, className, }: DataGridProps<T>): import("react").JSX.Element;
102
+ export type { TableSort, SortDirection };