@tonycodes-ui/mortar 0.12.0 → 0.14.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.
@@ -3,6 +3,7 @@ import { type ReactNode } from "react";
3
3
  import { type Tone } from "./primitives.js";
4
4
  import { type SignInProvider } from "./auth.js";
5
5
  import { type HeadingLevel } from "./heading.js";
6
+ import { type FlyoutItem } from "./internal.js";
6
7
  /**
7
8
  * A navigation link; `icon` replaces the default marker in the sidebar. With
8
9
  * `children` the item becomes a disclosure: its own `href` is the first link
@@ -55,29 +56,41 @@ export interface StackedShellProps {
55
56
  brand: string;
56
57
  logo?: ReactNode;
57
58
  homeHref?: string;
58
- navigation: LinkItem[];
59
+ /** Top-level links, or labelled groups that open a dropdown panel. */
60
+ navigation: NavbarItem[];
59
61
  actions?: ReactNode;
60
62
  /** Page heading shown above the content, e.g. a PageHeading. */
61
63
  header?: ReactNode;
62
64
  width?: "md" | "lg" | "xl" | "full";
65
+ /** The bar's surface: default, inverse (the other appearance) or accent (the brand's accent fill). */
66
+ tone?: NavbarTone;
67
+ /** A second row of page tabs under the bar, rendered as a TabNav named by `label`. */
68
+ tabs?: ItemGroup<TabNavItem>;
63
69
  children: ReactNode;
64
70
  className?: string;
65
71
  }
66
72
  /** Top navigation with a centred page column: Tailwind's stacked application layout. */
67
- export declare function StackedShell({ brand, logo, homeHref, navigation, actions, header, width, children, className, }: StackedShellProps): import("react").JSX.Element;
73
+ export declare function StackedShell({ brand, logo, homeHref, navigation, actions, header, width, tone, tabs, children, className, }: StackedShellProps): import("react").JSX.Element;
74
+ /** A labelled group of links that opens a dropdown panel from the bar. */
75
+ export type NavbarGroup = ItemGroup<FlyoutItem>;
76
+ /** A top-level link, or a group; a group holding the current page is marked current. */
77
+ export type NavbarItem = LinkItem | NavbarGroup;
78
+ export type NavbarTone = "default" | "inverse" | "accent";
68
79
  export interface NavbarProps {
69
80
  brand: string;
70
81
  logo?: ReactNode;
71
82
  homeHref?: string;
72
- /** Top-level links; the navbar has no sub-menus. */
73
- items: LinkItem[];
83
+ /** Top-level links, or labelled groups that open a dropdown panel. */
84
+ items: NavbarItem[];
74
85
  actions?: ReactNode;
86
+ /** The bar's surface: default, inverse (the other appearance) or accent (the brand's accent fill). */
87
+ tone?: NavbarTone;
75
88
  /** Accessible name of the navigation landmark. */
76
89
  label?: string;
77
90
  className?: string;
78
91
  }
79
92
  /** Horizontal application navigation that collapses into a menu on narrow screens. */
80
- export declare function Navbar({ brand, logo, homeHref, items, actions, label, className, }: NavbarProps): import("react").JSX.Element;
93
+ export declare function Navbar({ brand, logo, homeHref, items, actions, tone, label, className, }: NavbarProps): import("react").JSX.Element;
81
94
  export interface BreadcrumbItem {
82
95
  label: string;
83
96
  href?: string;
@@ -198,6 +211,18 @@ export interface DataTableColumn<T> {
198
211
  width?: string;
199
212
  /** Clip long values to one line with an ellipsis. */
200
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";
201
226
  }
202
227
  export interface DataTableProps<T extends {
203
228
  id: string;
@@ -5,7 +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 { LinkContent, NavGroups, NavTreeLinks, MobileNavDialog, TermList, cx, componentRoot, classedIntroSlots, useDomId, } from "./internal.js";
8
+ import { Flyout, LinkContent, NavGroups, NavTreeLinks, MobileNavDialog, TermList, cx, componentRoot, classedIntroSlots, sectionTone, useDomId, } from "./internal.js";
9
9
  function SidebarContent({ brand, logo, workspace, homeHref, navigation, sections = [], footer, label = "Primary", onNavigate, }) {
10
10
  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 })] }));
11
11
  }
@@ -29,15 +29,16 @@ export function AppShell({ brand, logo, workspace, homeHref, footer, navigation,
29
29
  return (_jsxs("div", { ...componentRoot("AppShell"), className: cx("m-app-shell", className), children: [_jsx(KitLink, { className: "m-skip", href: `#${contentId}`, children: "Skip to content" }), _jsx("aside", { className: "m-sidebar", children: _jsx(SidebarContent, { ...sidebar }) }), _jsxs("div", { className: "m-app-main", children: [_jsxs("header", { className: "m-app-header", children: [_jsx(Button, { variant: "ghost", className: "m-menu-trigger", "aria-haspopup": "dialog", "aria-expanded": open, onClick: () => setOpen(true), children: "Menu" }), _jsx("div", { className: "m-header-context", children: header || workspace || brand }), _jsx("div", { className: "m-actions", children: actions })] }), aside ? (_jsxs("div", { className: "m-app-columns", children: [main, _jsx("aside", { className: "m-app-aside", "aria-label": asideLabel, children: aside })] })) : (main)] }), _jsx(MobileNavDialog, { open: open, onClose: () => setOpen(false), title: brand, children: _jsx(SidebarContent, { ...sidebar, onNavigate: () => setOpen(false) }) })] }));
30
30
  }
31
31
  /** Top navigation with a centred page column: Tailwind's stacked application layout. */
32
- export function StackedShell({ brand, logo, homeHref, navigation, actions, header, width = "lg", children, className, }) {
32
+ export function StackedShell({ brand, logo, homeHref, navigation, actions, header, width = "lg", tone, tabs, children, className, }) {
33
33
  const contentId = useDomId("m-stacked-");
34
- return (_jsxs("div", { ...componentRoot("StackedShell"), className: cx("m-stacked-shell", className), children: [_jsx(KitLink, { className: "m-skip", href: `#${contentId}`, children: "Skip to content" }), _jsx(Navbar, { brand: brand, logo: logo, homeHref: homeHref, items: navigation, actions: actions }), _jsxs("main", { id: contentId, tabIndex: -1, "data-width": width, children: [header && _jsx("div", { className: "m-stacked-header", children: header }), children] })] }));
34
+ return (_jsxs("div", { ...componentRoot("StackedShell"), className: cx("m-stacked-shell", className), children: [_jsx(KitLink, { className: "m-skip", href: `#${contentId}`, children: "Skip to content" }), _jsx(Navbar, { brand: brand, logo: logo, homeHref: homeHref, items: navigation, actions: actions, tone: tone }), tabs && (_jsx("div", { className: "m-stacked-tabs", children: _jsx(TabNav, { label: tabs.label, items: tabs.items }) })), _jsxs("main", { id: contentId, tabIndex: -1, "data-width": width, children: [header && _jsx("div", { className: "m-stacked-header", children: header }), children] })] }));
35
35
  }
36
36
  /** Horizontal application navigation that collapses into a menu on narrow screens. */
37
- export function Navbar({ brand, logo, homeHref = "/", items, actions, label = "Primary", className, }) {
37
+ export function Navbar({ brand, logo, homeHref = "/", items, actions, tone, label = "Primary", className, }) {
38
38
  const [open, setOpen] = useState(false);
39
39
  const id = useId();
40
- return (_jsxs("header", { ...componentRoot("Navbar"), className: cx("m-navbar", className), children: [_jsxs(KitLink, { className: "m-brand", href: homeHref, children: [_jsx(BrandMark, { logo: logo }), brand] }), _jsx(Button, { variant: "ghost", className: "m-navbar-toggle", "aria-expanded": open, "aria-controls": id, onClick: () => setOpen(!open), children: "Menu" }), _jsx("nav", { id: id, "aria-label": label, "data-open": open || undefined, children: items.map((item, index) => (_jsx(KitLink, { href: item.href, "aria-current": item.current ? "page" : undefined, onClick: () => setOpen(false), children: _jsx(LinkContent, { prefix: "nav", icon: item.icon, label: item.label, count: item.count }) }, `${item.label}:${item.href}:${index}`))) }), actions && _jsx("div", { className: "m-actions", children: actions })] }));
40
+ const close = () => setOpen(false);
41
+ return (_jsxs("header", { ...componentRoot("Navbar"), className: cx("m-navbar", className), "data-tone": sectionTone(tone), children: [_jsxs(KitLink, { className: "m-brand", href: homeHref, children: [_jsx(BrandMark, { logo: logo }), brand] }), _jsx(Button, { variant: "ghost", className: "m-navbar-toggle", "aria-expanded": open, "aria-controls": id, onClick: () => setOpen(!open), children: "Menu" }), _jsx("nav", { id: id, "aria-label": label, "data-open": open || undefined, children: items.map((item, index) => "items" in item ? (_jsx(Flyout, { label: item.label, items: item.items, onNavigate: close }, `${item.label}:group:${index}`)) : (_jsx(KitLink, { href: item.href, "aria-current": item.current ? "page" : undefined, onClick: close, children: _jsx(LinkContent, { prefix: "nav", icon: item.icon, label: item.label, count: item.count }) }, `${item.label}:${item.href}:${index}`))) }), actions && _jsx("div", { className: "m-actions", children: actions })] }));
41
42
  }
42
43
  /** Trail to the current page; the item without an href is the current page. */
43
44
  export function Breadcrumbs({ items, label = "Breadcrumb", separator = "slash", className, }) {
@@ -86,6 +87,15 @@ export function MetricGroup({ label, items, variant = "shared", className, }) {
86
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] }))] })),
87
88
  })) }));
88
89
  }
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
+ }
89
99
  const collator = new Intl.Collator(undefined, {
90
100
  numeric: true,
91
101
  sensitivity: "base",
@@ -171,12 +181,14 @@ export function DataTable({ caption, columns, rows, selectedIds = [], onSelectio
171
181
  ? selectedIds.filter((rowId) => rowId !== row.id)
172
182
  : [...selectedIds, row.id]) }) })), columns.map((col, index) => {
173
183
  const content = col.truncate ? (_jsx("span", { className: "m-truncate", children: col.render(row) })) : (col.render(row));
174
- return index === 0 ? (_jsx("th", { scope: "row", "data-align": columnAlign(col.align), "data-truncate": col.truncate || undefined, children: href ? (_jsx(KitLink, { className: "m-row-link", href: href, children: content })) : (content) }, col.key)) : (_jsx("td", { "data-align": columnAlign(col.align), "data-truncate": col.truncate || undefined, children: content }, col.key));
184
+ return index === 0 ? (_jsx("th", { scope: "row", ...columnLayout(col, index), "data-align": columnAlign(col.align), "data-truncate": col.truncate || undefined, children: href ? (_jsx(KitLink, { className: "m-row-link", href: href, children: content })) : (content) }, col.key)) : (_jsx("td", { ...columnLayout(col, index), "data-align": columnAlign(col.align), "data-truncate": col.truncate || undefined, children: content }, col.key));
175
185
  })] }, row.id));
176
186
  };
177
- return (_jsxs("section", { id: id, ...componentRoot("DataTable"), className: cx("m-data-table", className), "aria-label": caption, "data-density": density === "default" ? undefined : density, "data-striped": striped || undefined, children: [(toolbar || selectedIds.length > 0) && (_jsx("div", { className: "m-table-toolbar", children: selectedIds.length > 0 ? (_jsxs(_Fragment, { children: [_jsxs("strong", { children: [selectedIds.length, " selected"] }), _jsxs("div", { className: "m-actions", children: [bulkActions, _jsx(Button, { variant: "ghost", onClick: () => onSelectionChange?.([]), children: "Clear selection" })] })] })) : (toolbar) })), _jsx("p", { className: loading ? "m-table-state" : "m-sr-only", role: "status", "data-loading": loading || undefined, children: loading ? "Loading records…" : "" }), loading ? null : error ? (_jsx(Notice, { title: "Unable to load records", tone: "danger", announce: true, children: error })) : !rows.length ? (_jsx(EmptyState, { title: empty.title, description: empty.description, action: empty.action, headingLevel: headingLevel })) : (_jsx("div", { className: "m-table-scroll", role: "region", "aria-label": `${caption} scroll area`, tabIndex: 0, style: maxHeight ? { maxHeight } : undefined, "data-sticky": maxHeight ? true : undefined, children: _jsxs("table", { children: [_jsx("caption", { className: "m-sr-only", children: caption }), columns.some((col) => col.width) && (_jsxs("colgroup", { children: [onSelectionChange && _jsx("col", { className: "m-table-select-col" }), columns.map((col) => (_jsx("col", { style: col.width ? { width: col.width } : undefined }, col.key)))] })), _jsx("thead", { children: _jsxs("tr", { children: [onSelectionChange && (_jsx("th", { scope: "col", children: _jsx(SelectAll, { checked: allHere, partial: selectedHere.length > 0 && !allHere, onChange: toggleAll }) })), columns.map((col) => {
187
+ return (_jsxs("section", { id: id, ...componentRoot("DataTable"), className: cx("m-data-table", className), "aria-label": caption, "data-density": density === "default" ? undefined : density, "data-striped": striped || undefined, "data-prioritised": columns.some((col, index) => columnLayout(col, index)["data-priority"])
188
+ ? true
189
+ : undefined, children: [(toolbar || selectedIds.length > 0) && (_jsx("div", { className: "m-table-toolbar", children: selectedIds.length > 0 ? (_jsxs(_Fragment, { children: [_jsxs("strong", { children: [selectedIds.length, " selected"] }), _jsxs("div", { className: "m-actions", children: [bulkActions, _jsx(Button, { variant: "ghost", onClick: () => onSelectionChange?.([]), children: "Clear selection" })] })] })) : (toolbar) })), _jsx("p", { className: loading ? "m-table-state" : "m-sr-only", role: "status", "data-loading": loading || undefined, children: loading ? "Loading records…" : "" }), loading ? null : error ? (_jsx(Notice, { title: "Unable to load records", tone: "danger", announce: true, children: error })) : !rows.length ? (_jsx(EmptyState, { title: empty.title, description: empty.description, action: empty.action, headingLevel: headingLevel })) : (_jsx("div", { className: "m-table-scroll", role: "region", "aria-label": `${caption} scroll area`, tabIndex: 0, style: maxHeight ? { maxHeight } : undefined, "data-sticky": maxHeight ? true : undefined, children: _jsxs("table", { children: [_jsx("caption", { className: "m-sr-only", children: caption }), columns.some((col) => col.width) && (_jsxs("colgroup", { children: [onSelectionChange && _jsx("col", { className: "m-table-select-col" }), columns.map((col, index) => (_jsx("col", { ...columnLayout(col, index), style: col.width ? { width: col.width } : undefined }, col.key)))] })), _jsx("thead", { children: _jsxs("tr", { children: [onSelectionChange && (_jsx("th", { scope: "col", children: _jsx(SelectAll, { checked: allHere, partial: selectedHere.length > 0 && !allHere, onChange: toggleAll }) })), columns.map((col, index) => {
178
190
  const direction = sort?.key === col.key ? sort.direction : undefined;
179
- return (_jsx("th", { scope: "col", "data-align": columnAlign(col.align), "aria-sort": col.sortable ? direction || "none" : undefined, children: col.sortable ? (_jsxs("button", { type: "button", className: "m-sort-button", onClick: () => toggleSort(col.key), children: [col.label, _jsx(SortArrows, { direction: direction })] })) : (col.label) }, col.key));
191
+ return (_jsx("th", { scope: "col", ...columnLayout(col, index), "data-align": columnAlign(col.align), "aria-sort": col.sortable ? direction || "none" : undefined, children: col.sortable ? (_jsxs("button", { type: "button", className: "m-sort-button", onClick: () => toggleSort(col.key), children: [col.label, _jsx(SortArrows, { direction: direction })] })) : (col.label) }, col.key));
180
192
  })] }) }), groupBy ? (groupRows(rows, visibleRows, groupBy).map(([label, group]) => (_jsxs("tbody", { children: [_jsx(TableGroupRow, { label: label, span: span }), group.map(renderRow)] }, label)))) : (_jsx("tbody", { children: visibleRows.map(renderRow) }))] }) })), footer && _jsx("div", { className: "m-table-footer", children: footer })] }));
181
193
  }
182
194
  /** Plain semantic table for documents, settings summaries and comparisons without row actions. */
@@ -0,0 +1,38 @@
1
+ import { type BrandDefinition } from "./brand.js";
2
+ /** Literal colours (#rrggbb) and font stacks for an email. */
3
+ export interface EmailTheme {
4
+ /** The page behind the message. */
5
+ paper: string;
6
+ /** The message card. */
7
+ surface: string;
8
+ /** Recessed areas such as a one-time code. */
9
+ sunken: string;
10
+ line: string;
11
+ ink: string;
12
+ secondary: string;
13
+ muted: string;
14
+ primary: string;
15
+ onPrimary: string;
16
+ accent: string;
17
+ onAccent: string;
18
+ link: string;
19
+ /** A tint of primary on the paper, for highlighted rows and callouts. */
20
+ selected: string;
21
+ success: string;
22
+ warning: string;
23
+ danger: string;
24
+ info: string;
25
+ /** Body font stack, ending in fonts every email client has. */
26
+ font: string;
27
+ /** Heading font stack; the body stack unless the brand sets one. */
28
+ fontHeading: string;
29
+ mono: string;
30
+ }
31
+ /**
32
+ * The email theme for a brand, in its light appearance: emails render light,
33
+ * since most clients ignore or override a dark one. Without a brand, Mortar's
34
+ * neutral defaults. Brand colours must be literal (`var()`, `color-mix()`
35
+ * and `light-dark()` need a browser) and opaque; the accent gradient is not
36
+ * used, as most clients cannot paint one, so accents use the flat `accent`.
37
+ */
38
+ export declare function emailTheme(brand?: BrandDefinition): EmailTheme;
@@ -0,0 +1,200 @@
1
+ /* Email theme. Email clients cannot read Mortar's stylesheet: Gmail drops CSS
2
+ variables and Outlook for Windows renders with Word. So an email takes its
3
+ colours and fonts as literal values, resolved here from a brand the way
4
+ tokens.css resolves it for the light appearance: omitted values keep
5
+ Mortar's defaults or derive from primary, and derived colours
6
+ (color-mix(in oklab, …)) are computed in JS. tests/email.test.mjs checks
7
+ the defaults against tokens.css. */
8
+ import { isBrandFont } from "./brand.js";
9
+ /* The light defaults in tokens.css. */
10
+ const DEFAULTS = {
11
+ paper: "#ffffff",
12
+ surface: "#ffffff",
13
+ sunken: "#f5f5f7",
14
+ line: "#e5e5ea",
15
+ ink: "#000000",
16
+ secondary: "#3a3a3c",
17
+ muted: "#6e6e73",
18
+ primary: "#000000",
19
+ onPrimary: "#ffffff",
20
+ success: "#1f7a36",
21
+ warning: "#945700",
22
+ danger: "#c70014",
23
+ info: "#0060c7",
24
+ };
25
+ /* The neutral brand's tuned selected tint (no brand at all). */
26
+ const NEUTRAL_SELECTED = "#f2f2f4";
27
+ /* Mortar's system stack, plus the fonts Windows and Android mail apps have. */
28
+ const SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Helvetica, Arial, sans-serif';
29
+ const SERIF = 'Georgia, "Times New Roman", Times, serif';
30
+ const MONO = '"SF Mono", Menlo, Consolas, "Courier New", monospace';
31
+ const GENERIC = {
32
+ "sans-serif": SANS,
33
+ "system-ui": SANS,
34
+ "ui-sans-serif": SANS,
35
+ serif: SERIF,
36
+ "ui-serif": SERIF,
37
+ monospace: MONO,
38
+ "ui-monospace": MONO,
39
+ };
40
+ /**
41
+ * A brand font list for email: `var()` entries (which email cannot resolve)
42
+ * and generic families are dropped, and a stack every client has is
43
+ * appended, serif or monospace when the brand's generic family is one.
44
+ */
45
+ function fontStack(value, key) {
46
+ const text = value?.trim();
47
+ if (!text)
48
+ return undefined;
49
+ if (!isBrandFont(text))
50
+ throw new Error(`Invalid Mortar brand font for fonts.${key}: "${text}". Use family names, quoted names and generic families separated by commas, e.g. "Inter", sans-serif.`);
51
+ let fallback = SANS;
52
+ const names = text
53
+ .split(",")
54
+ .map((name) => name.trim())
55
+ .filter((name) => {
56
+ if (/^var\(/i.test(name))
57
+ return false;
58
+ const generic = GENERIC[name.toLowerCase()];
59
+ if (generic)
60
+ fallback = generic;
61
+ return !generic;
62
+ });
63
+ return [...names, fallback].join(", ");
64
+ }
65
+ const linear = (v) => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
66
+ const gamma = (v) => v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
67
+ function toOklab([r, g, b]) {
68
+ const [lr, lg, lb] = [r, g, b].map(linear);
69
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
70
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
71
+ const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
72
+ return [
73
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
74
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
75
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
76
+ ];
77
+ }
78
+ function fromOklab([L, a, b]) {
79
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
80
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
81
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
82
+ return [
83
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
84
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
85
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
86
+ ].map(gamma);
87
+ }
88
+ /** sRGB channels in 0–1 as #rrggbb, clipped to the sRGB gamut. */
89
+ function hex(rgb) {
90
+ return `#${rgb
91
+ .map((v) => Math.round(Math.min(1, Math.max(0, v)) * 255)
92
+ .toString(16)
93
+ .padStart(2, "0"))
94
+ .join("")}`;
95
+ }
96
+ /** A number, or a percentage of `whole`. */
97
+ function amount(value, whole) {
98
+ const n = parseFloat(value);
99
+ if (!/^[+-]?(?:\d+\.?\d*|\.\d+)%?$/.test(value) || Number.isNaN(n))
100
+ throw new Error();
101
+ return value.endsWith("%") ? (n / 100) * whole : n;
102
+ }
103
+ function hue(value) {
104
+ const m = /^([+-]?(?:\d+\.?\d*|\.\d+))(deg|turn|rad)?$/.exec(value);
105
+ if (!m)
106
+ throw new Error();
107
+ const n = parseFloat(m[1]);
108
+ return m[2] === "turn" ? n * 360 : m[2] === "rad" ? (n * 180) / Math.PI : n;
109
+ }
110
+ function hslToRgb(h, s, l) {
111
+ const k = (n) => (n + h / 30) % 12;
112
+ const a = s * Math.min(l, 1 - l);
113
+ return [0, 8, 4].map((n) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)));
114
+ }
115
+ function parseColour(value) {
116
+ const text = value.trim().toLowerCase();
117
+ if (text === "white")
118
+ return [1, 1, 1];
119
+ if (text === "black")
120
+ return [0, 0, 0];
121
+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(text);
122
+ if (short)
123
+ return short.slice(1).map((d) => parseInt(d + d, 16) / 255);
124
+ const long = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(text);
125
+ if (long)
126
+ return long.slice(1).map((d) => parseInt(d, 16) / 255);
127
+ const fn = /^(rgba?|hsla?|oklab|oklch)\(([^()]*)\)$/.exec(text);
128
+ if (!fn)
129
+ throw new Error();
130
+ const [channels, alpha] = fn[2].split("/");
131
+ const parts = channels.trim().split(/[\s,]+/);
132
+ const extraAlpha = parts.length === 4 ? parts.pop() : undefined;
133
+ const opacity = alpha ?? extraAlpha;
134
+ if (opacity !== undefined && amount(opacity.trim(), 1) !== 1)
135
+ throw new Error();
136
+ if (parts.length !== 3)
137
+ throw new Error();
138
+ const [x, y, z] = parts;
139
+ switch (fn[1]) {
140
+ case "rgb":
141
+ case "rgba":
142
+ return [x, y, z].map((v) => amount(v, 255) / 255);
143
+ case "hsl":
144
+ case "hsla":
145
+ return hslToRgb(hue(x), amount(y, 100) / 100, amount(z, 100) / 100);
146
+ case "oklab":
147
+ return fromOklab([amount(x, 1), amount(y, 0.4), amount(z, 0.4)]);
148
+ default: {
149
+ const c = amount(y, 0.4), h = (hue(z) * Math.PI) / 180;
150
+ return fromOklab([amount(x, 1), c * Math.cos(h), c * Math.sin(h)]);
151
+ }
152
+ }
153
+ }
154
+ function colour(value, key) {
155
+ const text = value?.trim();
156
+ if (!text)
157
+ return undefined;
158
+ try {
159
+ return hex(parseColour(text));
160
+ }
161
+ catch {
162
+ throw new Error(`Mortar email colours must be literal and opaque, for light.${key}: "${text}". Use a hex value, white, black, or rgb(), hsl(), oklab() or oklch().`);
163
+ }
164
+ }
165
+ /** color-mix(in oklab, a p%, b) as #rrggbb. */
166
+ function mix(a, b, percentA) {
167
+ const t = percentA / 100;
168
+ const [x, y] = [toOklab(parseColour(a)), toOklab(parseColour(b))];
169
+ return hex(fromOklab(x.map((v, i) => v * t + y[i] * (1 - t))));
170
+ }
171
+ /**
172
+ * The email theme for a brand, in its light appearance: emails render light,
173
+ * since most clients ignore or override a dark one. Without a brand, Mortar's
174
+ * neutral defaults. Brand colours must be literal (`var()`, `color-mix()`
175
+ * and `light-dark()` need a browser) and opaque; the accent gradient is not
176
+ * used, as most clients cannot paint one, so accents use the flat `accent`.
177
+ */
178
+ export function emailTheme(brand) {
179
+ const light = brand?.light ?? {};
180
+ const paper = colour(light.paper, "paper") ?? DEFAULTS.paper;
181
+ const primary = colour(light.primary, "primary") ?? DEFAULTS.primary;
182
+ const onPrimary = colour(light.onPrimary, "onPrimary") ?? DEFAULTS.onPrimary;
183
+ const font = fontStack(brand?.fonts?.body, "body") ?? SANS;
184
+ return {
185
+ ...DEFAULTS,
186
+ paper,
187
+ surface: colour(light.surface, "surface") ?? DEFAULTS.surface,
188
+ sunken: colour(light.sunken, "sunken") ?? DEFAULTS.sunken,
189
+ primary,
190
+ onPrimary,
191
+ accent: colour(light.accent, "accent") ?? primary,
192
+ onAccent: colour(light.onAccent, "onAccent") ?? onPrimary,
193
+ link: colour(light.link, "link") ?? primary,
194
+ selected: colour(light.selected, "selected") ??
195
+ (brand ? mix(primary, paper, 8) : NEUTRAL_SELECTED),
196
+ font,
197
+ fontHeading: fontStack(brand?.fonts?.heading, "heading") ?? font,
198
+ mono: MONO,
199
+ };
200
+ }
@@ -0,0 +1,100 @@
1
+ import { type ReactNode } from "react";
2
+ import { type EmailTheme } from "./email-theme.js";
3
+ export { emailTheme } from "./email-theme.js";
4
+ export type { EmailTheme } from "./email-theme.js";
5
+ export interface EmailLogo {
6
+ /** An absolute URL: the email is read away from your site. */
7
+ src: string;
8
+ alt: string;
9
+ width: number;
10
+ height: number;
11
+ }
12
+ export interface EmailShellProps {
13
+ /** The inbox preview line shown after the subject. */
14
+ preview: string;
15
+ /** From `emailTheme(brand)`; Mortar's neutral theme by default. */
16
+ theme?: EmailTheme;
17
+ logo?: EmailLogo;
18
+ /** Why the person received the email, and what to do if it wasn't for them. */
19
+ footer?: ReactNode;
20
+ lang?: string;
21
+ dir?: "ltr" | "rtl";
22
+ children: ReactNode;
23
+ }
24
+ /**
25
+ * The whole email: a card up to 600px wide on the sunken backdrop, with an
26
+ * optional logo above it and footer below. It sets the theme for the email
27
+ * components inside, and marks the email light-only so mail apps don't
28
+ * recolour the brand.
29
+ */
30
+ export declare function EmailShell({ preview, theme: given, logo, footer, lang, dir, children, }: EmailShellProps): import("react").JSX.Element;
31
+ export interface EmailHeadingProps {
32
+ /** 1 for the email's title (once per email), 2 for a section. */
33
+ level?: 1 | 2;
34
+ children: ReactNode;
35
+ }
36
+ export declare function EmailHeading({ level, children }: EmailHeadingProps): import("react").JSX.Element;
37
+ export interface EmailTextProps {
38
+ /** `muted` for secondary details such as an expiry time. */
39
+ tone?: "default" | "muted";
40
+ size?: "md" | "sm";
41
+ children: ReactNode;
42
+ }
43
+ /** A paragraph. 16px by default: email is read on phones, at arm's length. */
44
+ export declare function EmailText({ tone, size, children, }: EmailTextProps): import("react").JSX.Element;
45
+ export interface EmailButtonProps {
46
+ /** An absolute http(s) URL. */
47
+ href: string;
48
+ children: ReactNode;
49
+ }
50
+ /**
51
+ * The email's main action, on its own line. Padding is applied in a way
52
+ * Outlook for Windows keeps, so the whole button is clickable there too.
53
+ * Follow it with the URL as an EmailLink for clients that block buttons.
54
+ */
55
+ export declare function EmailButton({ href, children }: EmailButtonProps): import("react").JSX.Element;
56
+ export interface EmailLinkProps {
57
+ /** An absolute http(s) or mailto URL. */
58
+ href: string;
59
+ /** The URL itself when omitted, for "paste this link" fallbacks. */
60
+ children?: ReactNode;
61
+ }
62
+ export declare function EmailLink({ href, children }: EmailLinkProps): import("react").JSX.Element;
63
+ export interface EmailCodeProps {
64
+ /** A one-time code, shown large and spaced for reading and copying. */
65
+ code: string;
66
+ }
67
+ export declare function EmailCode({ code }: EmailCodeProps): import("react").JSX.Element;
68
+ export interface RenderedEmail {
69
+ html: string;
70
+ /** The plain-text alternative: send it with the HTML. */
71
+ text: string;
72
+ }
73
+ /**
74
+ * An email element as HTML and plain text, ready for a sending service
75
+ * (Resend, SES, Postmark…). Keep the HTML under about 100 KB: Gmail clips
76
+ * longer messages.
77
+ */
78
+ export declare function renderEmail(element: ReactNode): Promise<RenderedEmail>;
79
+ export interface VerifyEmailProps {
80
+ /** Your product, as the person knows it. */
81
+ productName: string;
82
+ /** A one-time code to type in, shown large. */
83
+ code?: string;
84
+ /** A confirmation link, shown as a button. Give `code`, `href` or both. */
85
+ href?: string;
86
+ /** The address being confirmed. */
87
+ recipient?: string;
88
+ /** Preformatted, e.g. "10 minutes". */
89
+ expiresIn?: string;
90
+ theme?: EmailTheme;
91
+ logo?: EmailLogo;
92
+ /** Replaces the default "if this wasn't you" footer. */
93
+ footer?: ReactNode;
94
+ lang?: string;
95
+ }
96
+ /**
97
+ * Confirms an email address with a code, a link or both: the email for the
98
+ * auth flow's verify-email step.
99
+ */
100
+ export declare function VerifyEmail({ productName, code, href, recipient, expiresIn, theme, logo, footer, lang, }: VerifyEmailProps): import("react").JSX.Element;
package/dist/email.js ADDED
@@ -0,0 +1,152 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /* Transactional email: @tonycodes-ui/mortar/email. Built on React Email,
3
+ which renders the table layout and inline styles email clients need; these
4
+ components give it Mortar's tokens, brand and copy. Nothing here uses
5
+ Mortar's stylesheet or app components, which email clients cannot run.
6
+ Requires the optional peer dependency @react-email/components. */
7
+ import { createContext, useContext, } from "react";
8
+ import { Body, Button, Container, Head, Heading, Html, Img, Link, Preview, Text, render, } from "@react-email/components";
9
+ import { emailTheme } from "./email-theme.js";
10
+ export { emailTheme } from "./email-theme.js";
11
+ const ThemeContext = createContext(undefined);
12
+ let neutral;
13
+ /** The theme from the enclosing EmailShell, or Mortar's neutral theme. */
14
+ function useTheme() {
15
+ return useContext(ThemeContext) ?? (neutral ??= emailTheme());
16
+ }
17
+ /* Links leave the mail client, so only web and mail addresses are allowed. */
18
+ function assertHref(href, component, mail = false) {
19
+ if (!(mail ? /^(?:https?:|mailto:)/i : /^https?:\/\//i).test(href.trim()))
20
+ throw new Error(`Mortar ${component} needs an absolute ${mail ? "http(s) or mailto" : "http(s)"} URL: "${href}"`);
21
+ }
22
+ /* A one-cell layout table. Outlook for Windows ignores padding, margins and
23
+ backgrounds on tables, so spacing and fills go on the cell. */
24
+ function Cell({ style, children, }) {
25
+ return (_jsx("table", { role: "presentation", width: "100%", border: 0, cellPadding: 0, cellSpacing: 0, children: _jsx("tbody", { children: _jsx("tr", { children: _jsx("td", { style: style, children: children }) }) }) }));
26
+ }
27
+ /**
28
+ * The whole email: a card up to 600px wide on the sunken backdrop, with an
29
+ * optional logo above it and footer below. It sets the theme for the email
30
+ * components inside, and marks the email light-only so mail apps don't
31
+ * recolour the brand.
32
+ */
33
+ export function EmailShell({ preview, theme: given, logo, footer, lang = "en", dir = "ltr", children, }) {
34
+ const theme = given ?? emailTheme();
35
+ if (logo)
36
+ assertHref(logo.src, "EmailShell logo");
37
+ return (_jsx(ThemeContext.Provider, { value: theme, children: _jsxs(Html, { lang: lang, dir: dir, children: [_jsxs(Head, { children: [_jsx("meta", { name: "color-scheme", content: "light" }), _jsx("meta", { name: "supported-color-schemes", content: "light" })] }), _jsx(Preview, { children: preview }), _jsx(Body, { style: {
38
+ margin: 0,
39
+ padding: "32px 12px",
40
+ backgroundColor: theme.sunken,
41
+ color: theme.ink,
42
+ fontFamily: theme.font,
43
+ }, children: _jsxs(Container, { style: { width: "100%", maxWidth: "600px" }, children: [logo && (_jsx(Cell, { style: { padding: "0 0 24px" }, children: _jsx(Img, { src: logo.src, alt: logo.alt, width: logo.width, height: logo.height }) })), _jsx(Cell, { style: {
44
+ backgroundColor: theme.surface,
45
+ border: `1px solid ${theme.line}`,
46
+ borderRadius: "12px",
47
+ padding: "32px",
48
+ }, children: children }), footer && (_jsx(Cell, { style: { padding: "24px 32px 0" }, children: _jsx(Text, { style: {
49
+ margin: 0,
50
+ fontFamily: theme.font,
51
+ fontSize: "12px",
52
+ lineHeight: "18px",
53
+ color: theme.muted,
54
+ }, children: footer }) }))] }) })] }) }));
55
+ }
56
+ export function EmailHeading({ level = 1, children }) {
57
+ const theme = useTheme();
58
+ return (_jsx(Heading, { as: level === 1 ? "h1" : "h2", style: {
59
+ margin: "0 0 16px",
60
+ fontFamily: theme.fontHeading,
61
+ fontSize: level === 1 ? "24px" : "18px",
62
+ lineHeight: level === 1 ? "32px" : "26px",
63
+ fontWeight: 600,
64
+ letterSpacing: "-0.02em",
65
+ color: theme.ink,
66
+ }, children: children }));
67
+ }
68
+ /** A paragraph. 16px by default: email is read on phones, at arm's length. */
69
+ export function EmailText({ tone = "default", size = "md", children, }) {
70
+ const theme = useTheme();
71
+ return (_jsx(Text, { style: {
72
+ margin: "0 0 16px",
73
+ fontFamily: theme.font,
74
+ fontSize: size === "md" ? "16px" : "14px",
75
+ lineHeight: size === "md" ? "24px" : "20px",
76
+ color: tone === "muted" ? theme.muted : theme.ink,
77
+ }, children: children }));
78
+ }
79
+ /**
80
+ * The email's main action, on its own line. Padding is applied in a way
81
+ * Outlook for Windows keeps, so the whole button is clickable there too.
82
+ * Follow it with the URL as an EmailLink for clients that block buttons.
83
+ */
84
+ export function EmailButton({ href, children }) {
85
+ const theme = useTheme();
86
+ assertHref(href, "EmailButton");
87
+ return (_jsx(Cell, { style: { padding: "8px 0 24px" }, children: _jsx(Button, { href: href, style: {
88
+ display: "inline-block",
89
+ backgroundColor: theme.primary,
90
+ color: theme.onPrimary,
91
+ fontFamily: theme.font,
92
+ fontSize: "16px",
93
+ lineHeight: "24px",
94
+ fontWeight: 600,
95
+ textDecoration: "none",
96
+ padding: "12px 24px",
97
+ borderRadius: "8px",
98
+ }, children: children }) }));
99
+ }
100
+ export function EmailLink({ href, children }) {
101
+ const theme = useTheme();
102
+ assertHref(href, "EmailLink", true);
103
+ return (_jsx(Link, { href: href, style: {
104
+ color: theme.link,
105
+ textDecoration: "underline",
106
+ wordBreak: "break-all",
107
+ }, children: children ?? href }));
108
+ }
109
+ export function EmailCode({ code }) {
110
+ const theme = useTheme();
111
+ return (_jsx(Cell, { style: { padding: "8px 0 24px" }, children: _jsx(Cell, { style: {
112
+ backgroundColor: theme.sunken,
113
+ borderRadius: "8px",
114
+ padding: "16px",
115
+ textAlign: "center",
116
+ }, children: _jsx(Text, { style: {
117
+ margin: 0,
118
+ fontFamily: theme.mono,
119
+ fontSize: "28px",
120
+ lineHeight: "36px",
121
+ fontWeight: 600,
122
+ letterSpacing: "0.2em",
123
+ color: theme.ink,
124
+ }, children: code }) }) }));
125
+ }
126
+ /**
127
+ * An email element as HTML and plain text, ready for a sending service
128
+ * (Resend, SES, Postmark…). Keep the HTML under about 100 KB: Gmail clips
129
+ * longer messages.
130
+ */
131
+ export async function renderEmail(element) {
132
+ const [html, text] = await Promise.all([
133
+ render(element),
134
+ render(element, { plainText: true }),
135
+ ]);
136
+ return { html, text };
137
+ }
138
+ /**
139
+ * Confirms an email address with a code, a link or both: the email for the
140
+ * auth flow's verify-email step.
141
+ */
142
+ export function VerifyEmail({ productName, code, href, recipient, expiresIn, theme, logo, footer, lang, }) {
143
+ if (!code && !href)
144
+ throw new Error("Mortar VerifyEmail needs a `code`, an `href` or both.");
145
+ const address = recipient ?? "your email address";
146
+ return (_jsxs(EmailShell, { preview: `Confirm your email address for ${productName}`, theme: theme, logo: logo, lang: lang, footer: footer ??
147
+ `You received this email because this address was used to sign up for ${productName}. If that wasn't you, you can ignore it.`, children: [_jsx(EmailHeading, { children: "Confirm your email address" }), code && (_jsxs(_Fragment, { children: [_jsxs(EmailText, { children: ["Enter this code in ", productName, " to confirm ", address, ":"] }), _jsx(EmailCode, { code: code })] })), href && (_jsxs(_Fragment, { children: [_jsx(EmailText, { children: code
148
+ ? "Or confirm with one click:"
149
+ : `Confirm ${address} to finish setting up your ${productName} account.` }), _jsx(EmailButton, { href: href, children: "Confirm email address" }), _jsxs(EmailText, { tone: "muted", size: "sm", children: ["If the button doesn't work, paste this link into your browser:", " ", _jsx(EmailLink, { href: href })] })] })), expiresIn && (_jsx(EmailText, { tone: "muted", size: "sm", children: code && href
150
+ ? `This code and link expire in ${expiresIn}.`
151
+ : `This ${code ? "code" : "link"} expires in ${expiresIn}.` }))] }));
152
+ }