@tonycodes-ui/mortar 0.16.0 → 0.16.2

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,178 @@
1
+ /* Native theme. SwiftUI and Jetpack Compose cannot read Mortar's stylesheet,
2
+ so a native app takes its colours as literal values, resolved here from a
3
+ brand for both appearances the way tokens.css resolves them: omitted values
4
+ keep Mortar's defaults or derive from primary, and derived colours
5
+ (color-mix(in oklab, …)) are computed in JS. scripts/native-tokens.mjs
6
+ writes the defaults and scales into the Swift and Kotlin token files, and
7
+ tests/native.test.mjs checks them against tokens.css. */
8
+ import { isBrandFont, } from "./brand.js";
9
+ import { hex, mix, parseColour } from "./colour.js";
10
+ /* The appearance defaults in tokens.css. */
11
+ const LIGHT = {
12
+ paper: "#ffffff",
13
+ surface: "#ffffff",
14
+ sunken: "#f5f5f7",
15
+ line: "#e5e5ea",
16
+ lineStrong: "#8b8b90",
17
+ ink: "#000000",
18
+ secondary: "#3a3a3c",
19
+ muted: "#6e6e73",
20
+ success: "#1f7a36",
21
+ warning: "#945700",
22
+ danger: "#c70014",
23
+ info: "#0060c7",
24
+ onFeedback: "#ffffff",
25
+ primary: "#000000",
26
+ onPrimary: "#ffffff",
27
+ codeBackground: "#000000",
28
+ codeInk: "#f5f5f7",
29
+ codeDim: "#8b8b90",
30
+ };
31
+ const DARK = {
32
+ paper: "#000000",
33
+ surface: "#0e0e10",
34
+ sunken: "#1c1c1e",
35
+ line: "#29292c",
36
+ lineStrong: "#727278",
37
+ ink: "#f5f5f7",
38
+ secondary: "#c7c7cc",
39
+ muted: "#98989d",
40
+ success: "#30d158",
41
+ warning: "#ffd60a",
42
+ danger: "#ff6961",
43
+ info: "#5aa9ff",
44
+ onFeedback: "#000000",
45
+ primary: "#ffffff",
46
+ onPrimary: "#000000",
47
+ codeBackground: "#0e0e10",
48
+ codeInk: "#f5f5f7",
49
+ codeDim: "#8b8b90",
50
+ };
51
+ /* The neutral brand's tuned interaction states (no brand at all). */
52
+ const NEUTRAL = {
53
+ light: {
54
+ primaryHover: "#29292c",
55
+ primaryActive: "#3a3a3c",
56
+ selected: "#f2f2f4",
57
+ },
58
+ dark: {
59
+ primaryHover: "#e5e5ea",
60
+ primaryActive: "#c7c7cc",
61
+ selected: "#1c1c1e",
62
+ },
63
+ };
64
+ function colour(value, mode, key) {
65
+ const text = value?.trim();
66
+ if (!text)
67
+ return undefined;
68
+ try {
69
+ return hex(parseColour(text));
70
+ }
71
+ catch {
72
+ throw new Error(`Mortar native colours must be literal and opaque, for ${mode}.${key}: "${text}". Use a hex value, white, black, or rgb(), hsl(), oklab() or oklch().`);
73
+ }
74
+ }
75
+ function palette(tokens, mode, branded) {
76
+ const base = mode === "light" ? LIGHT : DARK;
77
+ const own = (key) => colour(tokens?.[key], mode, key);
78
+ const paper = own("paper") ?? base.paper;
79
+ const primary = own("primary") ?? base.primary;
80
+ const onPrimary = own("onPrimary") ?? base.onPrimary;
81
+ const neutral = NEUTRAL[mode];
82
+ return {
83
+ ...base,
84
+ paper,
85
+ surface: own("surface") ?? base.surface,
86
+ sunken: own("sunken") ?? base.sunken,
87
+ primary,
88
+ primaryHover: own("primaryHover") ??
89
+ (branded ? mix(primary, base.ink, 85) : neutral.primaryHover),
90
+ primaryActive: own("primaryActive") ??
91
+ (branded ? mix(primary, base.ink, 72) : neutral.primaryActive),
92
+ onPrimary,
93
+ accent: own("accent") ?? primary,
94
+ onAccent: own("onAccent") ?? onPrimary,
95
+ focus: own("focus") ?? primary,
96
+ // Dark links default to ink: a dark primary is often too pale for text.
97
+ link: own("link") ?? (mode === "light" ? primary : base.ink),
98
+ selected: own("selected") ??
99
+ (branded
100
+ ? mix(primary, paper, mode === "light" ? 8 : 10)
101
+ : neutral.selected),
102
+ };
103
+ }
104
+ const GENERIC = {
105
+ "sans-serif": "sans-serif",
106
+ "system-ui": "sans-serif",
107
+ "ui-sans-serif": "sans-serif",
108
+ serif: "serif",
109
+ "ui-serif": "serif",
110
+ monospace: "monospace",
111
+ "ui-monospace": "monospace",
112
+ };
113
+ /**
114
+ * A brand font list as family names and a generic family. `var()` entries
115
+ * (which only a browser resolves) and the web's system aliases are dropped;
116
+ * the app bundles or registers the named families itself.
117
+ */
118
+ function font(value, key) {
119
+ const text = value?.trim();
120
+ if (!text)
121
+ return undefined;
122
+ if (!isBrandFont(text))
123
+ 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.`);
124
+ let generic = "sans-serif";
125
+ const families = [];
126
+ for (const entry of text.split(",")) {
127
+ const name = entry.trim().replace(/^(["'])(.*)\1$/, "$2");
128
+ const kind = GENERIC[name.toLowerCase()];
129
+ if (kind)
130
+ generic = kind;
131
+ else if (!/^var\(/i.test(name) && !/^-apple-system$/i.test(name))
132
+ families.push(name);
133
+ }
134
+ return { families, generic };
135
+ }
136
+ const SYSTEM = { families: [], generic: "sans-serif" };
137
+ const SYSTEM_MONO = { families: [], generic: "monospace" };
138
+ /**
139
+ * The native theme for a brand: literal light and dark colours and its fonts.
140
+ * Without a brand, Mortar's neutral defaults, the values in the generated
141
+ * Swift and Kotlin token files. Brand colours must be literal (`var()`,
142
+ * `color-mix()` and `light-dark()` need a browser) and opaque; the accent
143
+ * gradient is not used, so accents use the flat `accent`.
144
+ */
145
+ export function nativeTheme(brand) {
146
+ const body = font(brand?.fonts?.body, "body") ?? SYSTEM;
147
+ return {
148
+ light: palette(brand?.light, "light", Boolean(brand)),
149
+ dark: palette(brand?.dark, "dark", Boolean(brand)),
150
+ fonts: {
151
+ body,
152
+ heading: font(brand?.fonts?.heading, "heading") ?? body,
153
+ mono: SYSTEM_MONO,
154
+ },
155
+ };
156
+ }
157
+ /** Appearance-independent scales from tokens.css, in points (dp on Android). */
158
+ export const NATIVE_SCALES = {
159
+ space: { 1: 4, 2: 8, 3: 12, 4: 16, 6: 24, 8: 32, 10: 40, 12: 48 },
160
+ radius: { xs: 2, sm: 4, md: 8, lg: 12, xl: 16, full: 999 },
161
+ weight: { regular: 400, medium: 500, semibold: 600, bold: 700 },
162
+ /** Letter spacing, in em. */
163
+ tracking: { display: -0.04, heading: -0.02, body: 0, caps: 0.04 },
164
+ /** Line height, as a multiple of the font size. */
165
+ leading: { display: 1.1, heading: 1.3, body: 1.6 },
166
+ /** Control height, padding, font size and row padding per density. */
167
+ density: {
168
+ compact: { control: 30, pad: 10, fontSize: 13, rowPad: 10 },
169
+ comfortable: { control: 36, pad: 14, fontSize: 14, rowPad: 14 },
170
+ spacious: { control: 44, pad: 18, fontSize: 15, rowPad: 18 },
171
+ },
172
+ icon: 16,
173
+ focusOffset: 3,
174
+ /** The minimum hit size on touch screens. */
175
+ touchTarget: 44,
176
+ /** The opacity of the black scrim behind sheets and dialogs. */
177
+ scrimOpacity: 0.5,
178
+ };
package/docs/native.md ADDED
@@ -0,0 +1,36 @@
1
+ # Native apps
2
+
3
+ Mortar is coming to iPhone, iPad and Android as a SwiftUI package and a Jetpack Compose library, tracked in [#95](https://github.com/tonycodes/mortar/issues/95). This page covers what exists so far: the design tokens both libraries are built on.
4
+
5
+ ## Tokens
6
+
7
+ SwiftUI and Compose cannot read `tokens.css`, so each library gets its tokens as literal values in a generated file:
8
+
9
+ | Platform | File | Colours |
10
+ | -------- | ------------------------------------------------------------------------- | -------------------------------------------------- |
11
+ | Apple | `native/apple/Sources/Mortar/MortarTokens.swift` | `UInt32`, `0xRRGGBB` |
12
+ | Android | `native/android/mortar/src/main/kotlin/codes/tony/mortar/MortarTokens.kt` | `Long`, `0xFFRRGGBB`, the form `Color(Long)` takes |
13
+
14
+ Each file holds:
15
+
16
+ - `MortarTokens.light` and `MortarTokens.dark`: a `MortarPalette` for each appearance. Its colours mirror the `--m-*` tokens: `paper`, `surface`, `sunken`, `line`, `lineStrong`, `ink`, `secondary`, `muted`, the four status colours and `onFeedback`, `primary` with `primaryHover`, `primaryActive` and `onPrimary`, `accent` and `onAccent`, `focus`, `link`, `selected`, and the code block colours.
17
+ - `MortarTokens.compact`, `comfortable` and `spacious`: a `MortarDensity` with the control height, padding, font size and row padding.
18
+ - The scales, named after their CSS properties: `space1` to `space12`, `radiusXs` to `radiusFull` (`radius` is `--m-radius`), `weightRegular` to `weightBold`, `trackingDisplay` to `trackingCaps` (in em), `leadingDisplay` to `leadingBody`, `icon`, `focusOffset`, `touchTarget` and `scrimOpacity`. Sizes are in points on Apple and dp on Android.
19
+
20
+ `touchTarget` is Mortar's 44. Material asks for 48dp on Android, so the Compose components will use the larger of the two.
21
+
22
+ ## Brands
23
+
24
+ `nativeTheme(brand)` in `src/native-theme.ts` resolves a `BrandDefinition` to literal light and dark palettes the way `tokens.css` resolves it: omitted values keep the defaults or derive from primary, and `color-mix(in oklab, …)` tints are computed in JS. Brand colours must be literal and opaque (hex, `white`, `black`, `rgb()`, `hsl()`, `oklab()` or `oklch()`). Accents use the flat `accent`, not the gradient. Fonts become family names plus a generic family; the app bundles the fonts itself.
25
+
26
+ It isn't a public entry point yet. The Swift and Kotlin libraries will load a resolved brand at runtime.
27
+
28
+ ## Changing tokens
29
+
30
+ `src/native-theme.ts` holds the defaults and scales; `tests/native.test.mjs` fails when they differ from `tokens.css`, or when a brand resolves differently from the CSS. After changing either, regenerate the files:
31
+
32
+ ```sh
33
+ npm run native:tokens
34
+ ```
35
+
36
+ The test also fails while the generated files are out of date, and compiles them with `swiftc` (Swift 6 language mode) and `kotlinc` when those are installed. CI requires both compilers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tonycodes-ui/mortar",
3
- "version": "0.16.0",
3
+ "version": "0.16.2",
4
4
  "description": "Mortar: a shared design foundation, application and marketing UI for React and Tailwind.",
5
5
  "type": "module",
6
6
  "files": [
@@ -58,6 +58,7 @@
58
58
  "build:playground": "tsc --noEmit -p tsconfig.playground.json && vite build",
59
59
  "format:check": "prettier --check .",
60
60
  "release:prepare": "node scripts/release.mjs",
61
+ "native:tokens": "npm run build && node scripts/native-tokens.mjs",
61
62
  "test:visual": "playwright test --config playwright.visual.config.mjs"
62
63
  },
63
64
  "peerDependencies": {
package/src/colour.ts ADDED
@@ -0,0 +1,115 @@
1
+ /* Colour maths for brands resolved outside a browser (email, native apps):
2
+ the opaque colour syntax a brand can resolve without one, converted to sRGB
3
+ and written as #rrggbb, and color-mix(in oklab, …) as tokens.css uses it.
4
+ tests/email.test.mjs checks the conversions against Chromium's. */
5
+
6
+ export type Rgb = [number, number, number];
7
+
8
+ const linear = (v: number) =>
9
+ v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
10
+ const gamma = (v: number) =>
11
+ v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
12
+
13
+ function toOklab([r, g, b]: Rgb): Rgb {
14
+ const [lr, lg, lb] = [r, g, b].map(linear);
15
+ const l = Math.cbrt(
16
+ 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb,
17
+ );
18
+ const m = Math.cbrt(
19
+ 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb,
20
+ );
21
+ const s = Math.cbrt(
22
+ 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb,
23
+ );
24
+ return [
25
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
26
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
27
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
28
+ ];
29
+ }
30
+ function fromOklab([L, a, b]: Rgb): Rgb {
31
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
32
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
33
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
34
+ return [
35
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
36
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
37
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
38
+ ].map(gamma) as Rgb;
39
+ }
40
+
41
+ /** sRGB channels in 0–1 as #rrggbb, clipped to the sRGB gamut. */
42
+ export function hex(rgb: Rgb): string {
43
+ return `#${rgb
44
+ .map((v) =>
45
+ Math.round(Math.min(1, Math.max(0, v)) * 255)
46
+ .toString(16)
47
+ .padStart(2, "0"),
48
+ )
49
+ .join("")}`;
50
+ }
51
+
52
+ /** A number, or a percentage of `whole`. */
53
+ function amount(value: string, whole: number): number {
54
+ const n = parseFloat(value);
55
+ if (!/^[+-]?(?:\d+\.?\d*|\.\d+)%?$/.test(value) || Number.isNaN(n))
56
+ throw new Error();
57
+ return value.endsWith("%") ? (n / 100) * whole : n;
58
+ }
59
+ function hue(value: string): number {
60
+ const m = /^([+-]?(?:\d+\.?\d*|\.\d+))(deg|turn|rad)?$/.exec(value);
61
+ if (!m) throw new Error();
62
+ const n = parseFloat(m[1]);
63
+ return m[2] === "turn" ? n * 360 : m[2] === "rad" ? (n * 180) / Math.PI : n;
64
+ }
65
+
66
+ function hslToRgb(h: number, s: number, l: number): Rgb {
67
+ const k = (n: number) => (n + h / 30) % 12;
68
+ const a = s * Math.min(l, 1 - l);
69
+ return [0, 8, 4].map(
70
+ (n) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)),
71
+ ) as Rgb;
72
+ }
73
+
74
+ /** sRGB channels in 0–1; throws for anything but opaque literal syntax. */
75
+ export function parseColour(value: string): Rgb {
76
+ const text = value.trim().toLowerCase();
77
+ if (text === "white") return [1, 1, 1];
78
+ if (text === "black") return [0, 0, 0];
79
+ const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(text);
80
+ if (short) return short.slice(1).map((d) => parseInt(d + d, 16) / 255) as Rgb;
81
+ const long = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(text);
82
+ if (long) return long.slice(1).map((d) => parseInt(d, 16) / 255) as Rgb;
83
+ const fn = /^(rgba?|hsla?|oklab|oklch)\(([^()]*)\)$/.exec(text);
84
+ if (!fn) throw new Error();
85
+ const [channels, alpha] = fn[2].split("/");
86
+ const parts = channels.trim().split(/[\s,]+/);
87
+ const extraAlpha = parts.length === 4 ? parts.pop() : undefined;
88
+ const opacity = alpha ?? extraAlpha;
89
+ if (opacity !== undefined && amount(opacity.trim(), 1) !== 1)
90
+ throw new Error();
91
+ if (parts.length !== 3) throw new Error();
92
+ const [x, y, z] = parts;
93
+ switch (fn[1]) {
94
+ case "rgb":
95
+ case "rgba":
96
+ return [x, y, z].map((v) => amount(v, 255) / 255) as Rgb;
97
+ case "hsl":
98
+ case "hsla":
99
+ return hslToRgb(hue(x), amount(y, 100) / 100, amount(z, 100) / 100);
100
+ case "oklab":
101
+ return fromOklab([amount(x, 1), amount(y, 0.4), amount(z, 0.4)]);
102
+ default: {
103
+ const c = amount(y, 0.4),
104
+ h = (hue(z) * Math.PI) / 180;
105
+ return fromOklab([amount(x, 1), c * Math.cos(h), c * Math.sin(h)]);
106
+ }
107
+ }
108
+ }
109
+
110
+ /** color-mix(in oklab, a p%, b) as #rrggbb. */
111
+ export function mix(a: string, b: string, percentA: number): string {
112
+ const t = percentA / 100;
113
+ const [x, y] = [toOklab(parseColour(a)), toOklab(parseColour(b))];
114
+ return hex(fromOklab(x.map((v, i) => v * t + y[i] * (1 - t)) as Rgb));
115
+ }
package/src/display.tsx CHANGED
@@ -1,3 +1,4 @@
1
+ import { KitImage, useImageFallback, type ImageFallback } from "./image.js";
1
2
  import { useId, type ReactNode } from "react";
2
3
  import { KitLink } from "./navigation.js";
3
4
  import type { Tone } from "./primitives.js";
@@ -45,6 +46,8 @@ export function Avatar({
45
46
  decorative = false,
46
47
  className,
47
48
  }: AvatarProps) {
49
+ // A broken or expired photo falls back to the placeholder.
50
+ const image = useImageFallback(src ?? "");
48
51
  return (
49
52
  <span
50
53
  {...componentRoot("Avatar")}
@@ -57,8 +60,13 @@ export function Avatar({
57
60
  "aria-label": status ? `${name}, ${status}` : name,
58
61
  })}
59
62
  >
60
- {src ? (
61
- <img src={src} alt="" />
63
+ {image.current ? (
64
+ <img
65
+ ref={image.ref}
66
+ src={image.current}
67
+ alt=""
68
+ onError={image.onError}
69
+ />
62
70
  ) : placeholder === "icon" ? (
63
71
  <Person className="m-avatar-placeholder" />
64
72
  ) : (
@@ -329,7 +337,8 @@ export interface GridListItem {
329
337
  /** Avatar or icon shown beside the title. */
330
338
  media?: ReactNode;
331
339
  /** Image across the top of the card. Use alt="" when the title already describes it. */
332
- cover?: { src: string; alt: string };
340
+ /** A cover image. `fallbackSrc` and `fallback` cover a missing or broken image. */
341
+ cover?: { src: string; alt: string } & ImageFallback;
333
342
  /** Badges, dates or counts under the description. */
334
343
  meta?: ReactNode;
335
344
  /** Term/value pairs under the body, e.g. a client card's last invoice and amount. */
@@ -372,7 +381,7 @@ export function GridList({
372
381
  <li key={item.id}>
373
382
  {item.cover && (
374
383
  <div className="m-grid-list-cover">
375
- <img src={item.cover.src} alt={item.cover.alt} loading="lazy" />
384
+ <KitImage {...item.cover} loading="lazy" />
376
385
  </div>
377
386
  )}
378
387
  <div className="m-grid-list-body">
package/src/ecommerce.tsx CHANGED
@@ -1,3 +1,4 @@
1
+ import { KitImage, type ImageFallback } from "./image.js";
1
2
  import {
2
3
  useEffect,
3
4
  useId,
@@ -26,7 +27,7 @@ import {
26
27
  cx,
27
28
  } from "./internal.js";
28
29
 
29
- export interface ProductImage {
30
+ export interface ProductImage extends ImageFallback {
30
31
  src: string;
31
32
  /** Describe the product shown; images are the main product information. */
32
33
  alt: string;
@@ -105,11 +106,7 @@ export function ProductList({
105
106
  return (
106
107
  <li key={product.id}>
107
108
  <div className="m-product-image">
108
- <img
109
- src={product.image.src}
110
- alt={product.image.alt}
111
- loading="lazy"
112
- />
109
+ <KitImage {...product.image} loading="lazy" />
113
110
  {product.badge && (
114
111
  <span className="m-product-badge">{product.badge}</span>
115
112
  )}
@@ -217,7 +214,7 @@ export function ProductOverview({
217
214
  <div className="m-product-gallery" data-gallery="grid">
218
215
  {images.map((image) => (
219
216
  <div key={image.src} className="m-product-image">
220
- <img src={image.src} alt={image.alt} />
217
+ <KitImage {...image} />
221
218
  </div>
222
219
  ))}
223
220
  </div>
@@ -225,7 +222,7 @@ export function ProductOverview({
225
222
  <div className="m-product-gallery">
226
223
  {shown && (
227
224
  <div className="m-product-image">
228
- <img src={shown.src} alt={shown.alt} />
225
+ <KitImage {...shown} />
229
226
  </div>
230
227
  )}
231
228
  {images.length > 1 && (
@@ -242,7 +239,7 @@ export function ProductOverview({
242
239
  aria-label={`Show image ${index + 1} of ${images.length}: ${image.alt}`}
243
240
  onClick={() => setCurrent(index)}
244
241
  >
245
- <img src={image.src} alt="" />
242
+ <KitImage {...image} alt="" />
246
243
  </button>
247
244
  ))}
248
245
  </div>
@@ -488,7 +485,7 @@ function CartLines({
488
485
  return (
489
486
  <li key={item.id}>
490
487
  <div className="m-product-image">
491
- <img src={item.image.src} alt={item.image.alt} loading="lazy" />
488
+ <KitImage {...item.image} loading="lazy" />
492
489
  </div>
493
490
  <div className="m-cart-info">
494
491
  <Heading className="m-cart-item-title">
@@ -1002,11 +999,7 @@ export function OrderHistory({
1002
999
  {order.items.map((item) => (
1003
1000
  <li key={item.id}>
1004
1001
  <div className="m-product-image">
1005
- <img
1006
- src={item.image.src}
1007
- alt={item.image.alt}
1008
- loading="lazy"
1009
- />
1002
+ <KitImage {...item.image} loading="lazy" />
1010
1003
  </div>
1011
1004
  <div>
1012
1005
  <p className="m-order-item-name">
@@ -7,6 +7,7 @@
7
7
  the defaults against tokens.css. */
8
8
 
9
9
  import { isBrandFont, type BrandDefinition } from "./brand.js";
10
+ import { hex, mix, parseColour } from "./colour.js";
10
11
 
11
12
  /** Literal colours (#rrggbb) and font stacks for an email. */
12
13
  export interface EmailTheme {
@@ -97,111 +98,6 @@ function fontStack(value: string | undefined, key: string): string | undefined {
97
98
  return [...names, fallback].join(", ");
98
99
  }
99
100
 
100
- /* Colour parsing: the opaque colour syntax a brand can resolve without a
101
- browser. Everything is converted to sRGB and written as #rrggbb. */
102
- type Rgb = [number, number, number];
103
-
104
- const linear = (v: number) =>
105
- v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
106
- const gamma = (v: number) =>
107
- v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
108
-
109
- function toOklab([r, g, b]: Rgb): Rgb {
110
- const [lr, lg, lb] = [r, g, b].map(linear);
111
- const l = Math.cbrt(
112
- 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb,
113
- );
114
- const m = Math.cbrt(
115
- 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb,
116
- );
117
- const s = Math.cbrt(
118
- 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb,
119
- );
120
- return [
121
- 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
122
- 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
123
- 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
124
- ];
125
- }
126
- function fromOklab([L, a, b]: Rgb): Rgb {
127
- const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
128
- const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
129
- const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
130
- return [
131
- 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
132
- -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
133
- -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
134
- ].map(gamma) as Rgb;
135
- }
136
-
137
- /** sRGB channels in 0–1 as #rrggbb, clipped to the sRGB gamut. */
138
- function hex(rgb: Rgb): string {
139
- return `#${rgb
140
- .map((v) =>
141
- Math.round(Math.min(1, Math.max(0, v)) * 255)
142
- .toString(16)
143
- .padStart(2, "0"),
144
- )
145
- .join("")}`;
146
- }
147
-
148
- /** A number, or a percentage of `whole`. */
149
- function amount(value: string, whole: number): number {
150
- const n = parseFloat(value);
151
- if (!/^[+-]?(?:\d+\.?\d*|\.\d+)%?$/.test(value) || Number.isNaN(n))
152
- throw new Error();
153
- return value.endsWith("%") ? (n / 100) * whole : n;
154
- }
155
- function hue(value: string): number {
156
- const m = /^([+-]?(?:\d+\.?\d*|\.\d+))(deg|turn|rad)?$/.exec(value);
157
- if (!m) throw new Error();
158
- const n = parseFloat(m[1]);
159
- return m[2] === "turn" ? n * 360 : m[2] === "rad" ? (n * 180) / Math.PI : n;
160
- }
161
-
162
- function hslToRgb(h: number, s: number, l: number): Rgb {
163
- const k = (n: number) => (n + h / 30) % 12;
164
- const a = s * Math.min(l, 1 - l);
165
- return [0, 8, 4].map(
166
- (n) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1)),
167
- ) as Rgb;
168
- }
169
-
170
- function parseColour(value: string): Rgb {
171
- const text = value.trim().toLowerCase();
172
- if (text === "white") return [1, 1, 1];
173
- if (text === "black") return [0, 0, 0];
174
- const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(text);
175
- if (short) return short.slice(1).map((d) => parseInt(d + d, 16) / 255) as Rgb;
176
- const long = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(text);
177
- if (long) return long.slice(1).map((d) => parseInt(d, 16) / 255) as Rgb;
178
- const fn = /^(rgba?|hsla?|oklab|oklch)\(([^()]*)\)$/.exec(text);
179
- if (!fn) throw new Error();
180
- const [channels, alpha] = fn[2].split("/");
181
- const parts = channels.trim().split(/[\s,]+/);
182
- const extraAlpha = parts.length === 4 ? parts.pop() : undefined;
183
- const opacity = alpha ?? extraAlpha;
184
- if (opacity !== undefined && amount(opacity.trim(), 1) !== 1)
185
- throw new Error();
186
- if (parts.length !== 3) throw new Error();
187
- const [x, y, z] = parts;
188
- switch (fn[1]) {
189
- case "rgb":
190
- case "rgba":
191
- return [x, y, z].map((v) => amount(v, 255) / 255) as Rgb;
192
- case "hsl":
193
- case "hsla":
194
- return hslToRgb(hue(x), amount(y, 100) / 100, amount(z, 100) / 100);
195
- case "oklab":
196
- return fromOklab([amount(x, 1), amount(y, 0.4), amount(z, 0.4)]);
197
- default: {
198
- const c = amount(y, 0.4),
199
- h = (hue(z) * Math.PI) / 180;
200
- return fromOklab([amount(x, 1), c * Math.cos(h), c * Math.sin(h)]);
201
- }
202
- }
203
- }
204
-
205
101
  function colour(value: string | undefined, key: string): string | undefined {
206
102
  const text = value?.trim();
207
103
  if (!text) return undefined;
@@ -214,13 +110,6 @@ function colour(value: string | undefined, key: string): string | undefined {
214
110
  }
215
111
  }
216
112
 
217
- /** color-mix(in oklab, a p%, b) as #rrggbb. */
218
- function mix(a: string, b: string, percentA: number): string {
219
- const t = percentA / 100;
220
- const [x, y] = [toOklab(parseColour(a)), toOklab(parseColour(b))];
221
- return hex(fromOklab(x.map((v, i) => v * t + y[i] * (1 - t)) as Rgb));
222
- }
223
-
224
113
  /**
225
114
  * The email theme for a brand, in its light appearance: emails render light,
226
115
  * since most clients ignore or override a dark one. Without a brand, Mortar's
@@ -1227,6 +1227,22 @@
1227
1227
  font-size: 12px;
1228
1228
  font-weight: var(--m-weight-bold);
1229
1229
  }
1230
+ /* A data-driven image that failed (KitImage, image.tsx): a placeholder that
1231
+ fills the container's reserved box. */
1232
+ .m-image-fallback {
1233
+ display: grid;
1234
+ place-items: center;
1235
+ width: 100%;
1236
+ height: 100%;
1237
+ /* Containers sized by aspect-ratio have no definite height to fill. */
1238
+ aspect-ratio: inherit;
1239
+ color: var(--m-muted);
1240
+ --m-icon-size: 28px;
1241
+ }
1242
+ .m-image-fallback svg {
1243
+ width: var(--m-icon-size);
1244
+ height: var(--m-icon-size);
1245
+ }
1230
1246
  .m-avatar img {
1231
1247
  width: 100%;
1232
1248
  height: 100%;
package/src/icons.tsx CHANGED
@@ -235,3 +235,14 @@ export function Circle() {
235
235
  </Icon>
236
236
  );
237
237
  }
238
+
239
+ /** A picture frame, for an image that failed to load. */
240
+ export function ImageMissing({ className }: { className?: string }) {
241
+ return (
242
+ <Icon className={className} stroke="currentColor" strokeWidth="1.5">
243
+ <rect x="2.75" y="3.75" width="14.5" height="12.5" rx="2" />
244
+ <circle cx="7.25" cy="8" r="1.5" />
245
+ <path d="m3 14.5 4.25-4 3 2.75 2.5-2.25 4.25 3.75" />
246
+ </Icon>
247
+ );
248
+ }