@tonycodes-ui/mortar 0.13.0 → 0.15.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.
@@ -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,6 @@
1
+ export { emailTheme } from "./email-theme.js";
2
+ export type { EmailTheme } from "./email-theme.js";
3
+ export { EmailShell, EmailHeading, EmailText, EmailButton, EmailLink, EmailCode, EmailCallout, EmailDivider, EmailSummary, renderEmail, } from "./email-components.js";
4
+ export type { EmailLogo, EmailShellProps, EmailHeadingProps, EmailTextProps, EmailButtonProps, EmailLinkProps, EmailCodeProps, EmailCalloutProps, EmailSummaryItem, EmailSummaryProps, RenderedEmail, } from "./email-components.js";
5
+ export { VerifyEmail, MagicLink, PasswordReset, Invite, Receipt, Notification, } from "./email-templates.js";
6
+ export type { EmailTemplateProps, VerifyEmailProps, MagicLinkProps, PasswordResetProps, InviteProps, ReceiptProps, NotificationProps, } from "./email-templates.js";
package/dist/email.js ADDED
@@ -0,0 +1,5 @@
1
+ /* @tonycodes-ui/mortar/email: transactional email built on React Email
2
+ (the optional peer dependency @react-email/components). See docs/email.md. */
3
+ export { emailTheme } from "./email-theme.js";
4
+ export { EmailShell, EmailHeading, EmailText, EmailButton, EmailLink, EmailCode, EmailCallout, EmailDivider, EmailSummary, renderEmail, } from "./email-components.js";
5
+ export { VerifyEmail, MagicLink, PasswordReset, Invite, Receipt, Notification, } from "./email-templates.js";
@@ -27,6 +27,8 @@ The playground has a page template for each step (`?recipe=<id>`).
27
27
  | Verify email | `verify-email` | AuthLayout, CodeInput, Button, a resend Button with a countdown, a "Change your email" link | `CodeInput` (`one-time-code`, `inputmode="numeric"`) |
28
28
  | Two-factor | `two-factor` | AuthLayout, CodeInput, Button, a ghost Button that switches to a recovery code | Authenticator: `CodeInput`. Recovery: `CodeInput alphanumeric length={8}` |
29
29
 
30
+ The emails for these steps come from `@tonycodes-ui/mortar/email`: `VerifyEmail` for verify email, `PasswordReset` for forgot password, and `MagicLink` for a passwordless sign-in with SignInPanel. See [Transactional email](email.md).
31
+
30
32
  ## Validation and errors
31
33
 
32
34
  - Validate on submit, not while the person is still typing. Clear a field's error as soon as they change it.
package/docs/email.md ADDED
@@ -0,0 +1,116 @@
1
+ # Transactional email
2
+
3
+ `@tonycodes-ui/mortar/email` renders emails that match your app: the same tokens, the same brand and copy that follows the [auth flows](auth-flows.md). It is built on [React Email](https://react.email), which produces the table layout and inline styles that email clients need.
4
+
5
+ Mortar's app components can't be used in email. Gmail strips stylesheets and CSS variables, and Outlook for Windows renders with Word, so an email needs its own markup. The email components take literal colours and fonts resolved from your brand instead.
6
+
7
+ ## Install
8
+
9
+ React Email is an optional peer dependency. Install it only in the app or service that sends email:
10
+
11
+ ```sh
12
+ npm install @react-email/components
13
+ ```
14
+
15
+ ## Render and send
16
+
17
+ ```tsx
18
+ import {
19
+ VerifyEmail,
20
+ emailTheme,
21
+ renderEmail,
22
+ } from "@tonycodes-ui/mortar/email";
23
+
24
+ const theme = emailTheme(tenant.brand); // the same BrandDefinition as ThemeProvider's brandTokens
25
+
26
+ const { html, text } = await renderEmail(
27
+ <VerifyEmail
28
+ productName="Hive"
29
+ code="482913"
30
+ recipient="ana@example.com"
31
+ expiresIn="10 minutes"
32
+ theme={theme}
33
+ logo={{
34
+ src: "https://hive.example/logo.png",
35
+ alt: "Hive",
36
+ width: 96,
37
+ height: 32,
38
+ }}
39
+ />,
40
+ );
41
+
42
+ await mailer.send({ to, subject: "Confirm your email address", html, text });
43
+ ```
44
+
45
+ `renderEmail` returns the HTML and its plain-text alternative. Send both. Sending is up to your app: Resend, SES, Postmark or any SMTP service.
46
+
47
+ ## The theme
48
+
49
+ `emailTheme(brand?)` resolves a brand to literal values for the **light** appearance, as `tokens.css` does:
50
+
51
+ - Omitted colours keep Mortar's defaults or derive from `primary`, as in the app. Derived tints such as `selected` (`color-mix(in oklab, …)`) are computed in JS.
52
+ - Brand colours must be literal and opaque: hex, `white`, `black`, `rgb()`, `hsl()`, `oklab()` or `oklch()`. Each is converted to `#rrggbb` exactly as Chromium paints it. `var()`, `color-mix()` and `light-dark()` need a browser, so they throw, as does a translucent colour.
53
+ - `accentGradient` is not used, because most clients can't paint a gradient.
54
+ - Brand fonts drop `var()` entries (from `next/font` and similar loaders) and end in a stack every client has: sans-serif, or serif or monospace when that is the brand's generic family. Web fonts load only in some clients, so the fallback is what most people see.
55
+ - Without a brand, you get Mortar's neutral theme.
56
+
57
+ Emails render light. Most clients either ignore a dark design or recolour it themselves, so the shell marks the email `color-scheme: light`.
58
+
59
+ ## Components
60
+
61
+ | Component | Use |
62
+ | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
63
+ | `EmailShell` | The whole email: the inbox `preview` line, an optional `logo`, a card up to 600px wide and a `footer`. It sets the theme for the components inside it. |
64
+ | `EmailHeading` | `level={1}` is the email's title (once per email); `level={2}` is a section. |
65
+ | `EmailText` | A paragraph, 16px. `tone="muted"` and `size="sm"` are for details such as an expiry time. |
66
+ | `EmailButton` | The main action. It keeps its padding in Outlook for Windows. Follow it with the URL as an `EmailLink`, for clients that block buttons. |
67
+ | `EmailLink` | An inline link. Without children it shows the URL itself. |
68
+ | `EmailCode` | A one-time code, large and spaced. |
69
+ | `EmailCallout` | A highlighted block with an optional `title`. `tone` (`info`, `success`, `warning`, `danger`) colours its edge; `neutral`, the default, is an aside such as a quoted message. |
70
+ | `EmailDivider` | A rule between sections. |
71
+ | `EmailSummary` | A receipt's `items` (name, preformatted `price`, optional `quantity` and `meta`), cost `lines` and `total`, as OrderSummary takes them. In the plain-text part it reads as rows. |
72
+
73
+ `EmailShell` takes `dir="rtl"`, and the components that place things at the start or end follow it: the callout's edge and the summary's amounts.
74
+
75
+ Links and the logo need absolute `http://` or `https://` URLs (`EmailLink` also takes `mailto:`), because the email is read away from your site. Anything else, such as a relative or `javascript:` URL, throws.
76
+
77
+ Compose your own email from these:
78
+
79
+ ```tsx
80
+ <EmailShell
81
+ preview="3 tasks are due this week"
82
+ theme={theme}
83
+ footer="You get this summary every Monday."
84
+ >
85
+ <EmailHeading>Your week in Hive</EmailHeading>
86
+ <EmailText>3 tasks are due this week.</EmailText>
87
+ <EmailCallout tone="warning" title="Overdue">
88
+ Launch checklist, due Friday
89
+ </EmailCallout>
90
+ <EmailButton href={tasksUrl}>Open your tasks</EmailButton>
91
+ </EmailShell>
92
+ ```
93
+
94
+ ## Templates
95
+
96
+ Every template takes `productName`, and optionally `theme`, `logo`, `footer` (replacing its "why you got this" line), `lang` and `dir`. Times and amounts are preformatted strings, so you choose the locale.
97
+
98
+ | Template | Use | Props |
99
+ | --------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
100
+ | `VerifyEmail` | The [verify-email step](auth-flows.md#steps) | A `code`, an `href` or both; optional `recipient`, `expiresIn` |
101
+ | `MagicLink` | A passwordless sign-in link, as SignInPanel sends | `href`; optional `expiresIn`, `requestedFrom` (e.g. "Chrome on macOS, near London") |
102
+ | `PasswordReset` | The [reset-password step](auth-flows.md#steps) | `href`; optional `recipient`, `expiresIn`, `requestedFrom` |
103
+ | `Invite` | An invitation to a workspace | `inviterName`, `href`; optional `workspaceName`, `message` (the inviter's note, quoted), `expiresIn` |
104
+ | `Receipt` | An order confirmation or receipt | `orderNumber`, `date`, `items`, `total`; optional `lines`, `paymentMethod`, `href` ("View order"), `title` |
105
+ | `Notification` | A product notification | `title`, `children` (a string becomes a paragraph); optional `action` (`{ label, href }`), `preview`, `preferencesHref` |
106
+
107
+ Send a password reset only to an address that has an account, and show the same "check your email" page either way, so the form never reveals whether an account exists.
108
+
109
+ ## Rules
110
+
111
+ - Say why the person got the email and what to do if it wasn't for them: the `footer`. The templates have one.
112
+ - Never put a one-time code in the `preview` line or the subject. Notifications show those on a locked screen.
113
+ - Give every image an absolute URL, `width`, `height` and `alt`.
114
+ - Don't rely on hover, scripts or forms. Email clients remove them.
115
+ - Keep each email under about 100 KB of HTML. Gmail clips longer messages behind a "View entire message" link.
116
+ - Before a release, check new emails in real clients (Gmail, Outlook for Windows, Apple Mail) with a service such as Litmus or Email on Acid.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonycodes-ui/mortar",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Mortar: a shared design foundation, application and marketing UI for React and Tailwind.",
5
5
  "type": "module",
6
6
  "files": [
@@ -36,6 +36,10 @@
36
36
  "./brand": {
37
37
  "types": "./dist/brand.d.ts",
38
38
  "import": "./dist/brand.js"
39
+ },
40
+ "./email": {
41
+ "types": "./dist/email.d.ts",
42
+ "import": "./dist/email.js"
39
43
  }
40
44
  },
41
45
  "sideEffects": [
@@ -59,7 +63,13 @@
59
63
  "peerDependencies": {
60
64
  "react": "^19.0.0",
61
65
  "react-dom": "^19.0.0",
62
- "tailwindcss": "^4.0.0"
66
+ "tailwindcss": "^4.0.0",
67
+ "@react-email/components": "^1.0.12"
68
+ },
69
+ "peerDependenciesMeta": {
70
+ "@react-email/components": {
71
+ "optional": true
72
+ }
63
73
  },
64
74
  "dependencies": {
65
75
  "@headlessui/react": "^2.2.0"
@@ -77,7 +87,8 @@
77
87
  "prettier": "^3.9.9",
78
88
  "@playwright/test": "^1.63.0",
79
89
  "@axe-core/playwright": "^4.13.0",
80
- "@modelcontextprotocol/sdk": "^1.32.1"
90
+ "@modelcontextprotocol/sdk": "^1.32.1",
91
+ "@react-email/components": "^1.0.12"
81
92
  },
82
93
  "license": "MIT",
83
94
  "publishConfig": {