@tonycodes-ui/mortar 0.16.1 → 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.
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
+ }
@@ -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
@@ -0,0 +1,256 @@
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
+
9
+ import {
10
+ isBrandFont,
11
+ type BrandAppearanceTokens,
12
+ type BrandDefinition,
13
+ } from "./brand.js";
14
+ import { hex, mix, parseColour } from "./colour.js";
15
+
16
+ /** One appearance's colours, as #rrggbb. */
17
+ export interface NativePalette {
18
+ /** The page background. */
19
+ paper: string;
20
+ /** Cards, panels and raised controls. */
21
+ surface: string;
22
+ /** Recessed areas: wells, muted bands and hover fills. */
23
+ sunken: string;
24
+ line: string;
25
+ /** Control borders and other lines that must reach 3:1. */
26
+ lineStrong: string;
27
+ ink: string;
28
+ secondary: string;
29
+ muted: string;
30
+ success: string;
31
+ warning: string;
32
+ danger: string;
33
+ info: string;
34
+ /** Text on a filled status colour. */
35
+ onFeedback: string;
36
+ primary: string;
37
+ /** Pressed-and-held and pointer hover. */
38
+ primaryHover: string;
39
+ /** Pressed. */
40
+ primaryActive: string;
41
+ onPrimary: string;
42
+ accent: string;
43
+ onAccent: string;
44
+ focus: string;
45
+ link: string;
46
+ /** A tint of primary on the paper, for selected rows and items. */
47
+ selected: string;
48
+ codeBackground: string;
49
+ codeInk: string;
50
+ codeDim: string;
51
+ }
52
+
53
+ /** A brand font: its family names, then the generic family to fall back to. */
54
+ export interface NativeFont {
55
+ /** Family names in order of preference; empty for the system font. */
56
+ families: string[];
57
+ generic: "sans-serif" | "serif" | "monospace";
58
+ }
59
+
60
+ /** Literal colours for both appearances, and fonts, for a native app. */
61
+ export interface NativeTheme {
62
+ light: NativePalette;
63
+ dark: NativePalette;
64
+ fonts: { body: NativeFont; heading: NativeFont; mono: NativeFont };
65
+ }
66
+
67
+ /* The appearance defaults in tokens.css. */
68
+ const LIGHT = {
69
+ paper: "#ffffff",
70
+ surface: "#ffffff",
71
+ sunken: "#f5f5f7",
72
+ line: "#e5e5ea",
73
+ lineStrong: "#8b8b90",
74
+ ink: "#000000",
75
+ secondary: "#3a3a3c",
76
+ muted: "#6e6e73",
77
+ success: "#1f7a36",
78
+ warning: "#945700",
79
+ danger: "#c70014",
80
+ info: "#0060c7",
81
+ onFeedback: "#ffffff",
82
+ primary: "#000000",
83
+ onPrimary: "#ffffff",
84
+ codeBackground: "#000000",
85
+ codeInk: "#f5f5f7",
86
+ codeDim: "#8b8b90",
87
+ };
88
+ const DARK: typeof LIGHT = {
89
+ paper: "#000000",
90
+ surface: "#0e0e10",
91
+ sunken: "#1c1c1e",
92
+ line: "#29292c",
93
+ lineStrong: "#727278",
94
+ ink: "#f5f5f7",
95
+ secondary: "#c7c7cc",
96
+ muted: "#98989d",
97
+ success: "#30d158",
98
+ warning: "#ffd60a",
99
+ danger: "#ff6961",
100
+ info: "#5aa9ff",
101
+ onFeedback: "#000000",
102
+ primary: "#ffffff",
103
+ onPrimary: "#000000",
104
+ codeBackground: "#0e0e10",
105
+ codeInk: "#f5f5f7",
106
+ codeDim: "#8b8b90",
107
+ };
108
+ /* The neutral brand's tuned interaction states (no brand at all). */
109
+ const NEUTRAL = {
110
+ light: {
111
+ primaryHover: "#29292c",
112
+ primaryActive: "#3a3a3c",
113
+ selected: "#f2f2f4",
114
+ },
115
+ dark: {
116
+ primaryHover: "#e5e5ea",
117
+ primaryActive: "#c7c7cc",
118
+ selected: "#1c1c1e",
119
+ },
120
+ };
121
+
122
+ type Mode = "light" | "dark";
123
+
124
+ function colour(
125
+ value: string | undefined,
126
+ mode: Mode,
127
+ key: string,
128
+ ): string | undefined {
129
+ const text = value?.trim();
130
+ if (!text) return undefined;
131
+ try {
132
+ return hex(parseColour(text));
133
+ } catch {
134
+ throw new Error(
135
+ `Mortar native colours must be literal and opaque, for ${mode}.${key}: "${text}". Use a hex value, white, black, or rgb(), hsl(), oklab() or oklch().`,
136
+ );
137
+ }
138
+ }
139
+
140
+ function palette(
141
+ tokens: BrandAppearanceTokens | undefined,
142
+ mode: Mode,
143
+ branded: boolean,
144
+ ): NativePalette {
145
+ const base = mode === "light" ? LIGHT : DARK;
146
+ const own = (key: keyof BrandAppearanceTokens) =>
147
+ colour(tokens?.[key], mode, key);
148
+ const paper = own("paper") ?? base.paper;
149
+ const primary = own("primary") ?? base.primary;
150
+ const onPrimary = own("onPrimary") ?? base.onPrimary;
151
+ const neutral = NEUTRAL[mode];
152
+ return {
153
+ ...base,
154
+ paper,
155
+ surface: own("surface") ?? base.surface,
156
+ sunken: own("sunken") ?? base.sunken,
157
+ primary,
158
+ primaryHover:
159
+ own("primaryHover") ??
160
+ (branded ? mix(primary, base.ink, 85) : neutral.primaryHover),
161
+ primaryActive:
162
+ own("primaryActive") ??
163
+ (branded ? mix(primary, base.ink, 72) : neutral.primaryActive),
164
+ onPrimary,
165
+ accent: own("accent") ?? primary,
166
+ onAccent: own("onAccent") ?? onPrimary,
167
+ focus: own("focus") ?? primary,
168
+ // Dark links default to ink: a dark primary is often too pale for text.
169
+ link: own("link") ?? (mode === "light" ? primary : base.ink),
170
+ selected:
171
+ own("selected") ??
172
+ (branded
173
+ ? mix(primary, paper, mode === "light" ? 8 : 10)
174
+ : neutral.selected),
175
+ };
176
+ }
177
+
178
+ const GENERIC: Record<string, NativeFont["generic"]> = {
179
+ "sans-serif": "sans-serif",
180
+ "system-ui": "sans-serif",
181
+ "ui-sans-serif": "sans-serif",
182
+ serif: "serif",
183
+ "ui-serif": "serif",
184
+ monospace: "monospace",
185
+ "ui-monospace": "monospace",
186
+ };
187
+
188
+ /**
189
+ * A brand font list as family names and a generic family. `var()` entries
190
+ * (which only a browser resolves) and the web's system aliases are dropped;
191
+ * the app bundles or registers the named families itself.
192
+ */
193
+ function font(value: string | undefined, key: string): NativeFont | undefined {
194
+ const text = value?.trim();
195
+ if (!text) return undefined;
196
+ if (!isBrandFont(text))
197
+ throw new Error(
198
+ `Invalid Mortar brand font for fonts.${key}: "${text}". Use family names, quoted names and generic families separated by commas, e.g. "Inter", sans-serif.`,
199
+ );
200
+ let generic: NativeFont["generic"] = "sans-serif";
201
+ const families: string[] = [];
202
+ for (const entry of text.split(",")) {
203
+ const name = entry.trim().replace(/^(["'])(.*)\1$/, "$2");
204
+ const kind = GENERIC[name.toLowerCase()];
205
+ if (kind) generic = kind;
206
+ else if (!/^var\(/i.test(name) && !/^-apple-system$/i.test(name))
207
+ families.push(name);
208
+ }
209
+ return { families, generic };
210
+ }
211
+
212
+ const SYSTEM: NativeFont = { families: [], generic: "sans-serif" };
213
+ const SYSTEM_MONO: NativeFont = { families: [], generic: "monospace" };
214
+
215
+ /**
216
+ * The native theme for a brand: literal light and dark colours and its fonts.
217
+ * Without a brand, Mortar's neutral defaults, the values in the generated
218
+ * Swift and Kotlin token files. Brand colours must be literal (`var()`,
219
+ * `color-mix()` and `light-dark()` need a browser) and opaque; the accent
220
+ * gradient is not used, so accents use the flat `accent`.
221
+ */
222
+ export function nativeTheme(brand?: BrandDefinition): NativeTheme {
223
+ const body = font(brand?.fonts?.body, "body") ?? SYSTEM;
224
+ return {
225
+ light: palette(brand?.light, "light", Boolean(brand)),
226
+ dark: palette(brand?.dark, "dark", Boolean(brand)),
227
+ fonts: {
228
+ body,
229
+ heading: font(brand?.fonts?.heading, "heading") ?? body,
230
+ mono: SYSTEM_MONO,
231
+ },
232
+ };
233
+ }
234
+
235
+ /** Appearance-independent scales from tokens.css, in points (dp on Android). */
236
+ export const NATIVE_SCALES = {
237
+ space: { 1: 4, 2: 8, 3: 12, 4: 16, 6: 24, 8: 32, 10: 40, 12: 48 },
238
+ radius: { xs: 2, sm: 4, md: 8, lg: 12, xl: 16, full: 999 },
239
+ weight: { regular: 400, medium: 500, semibold: 600, bold: 700 },
240
+ /** Letter spacing, in em. */
241
+ tracking: { display: -0.04, heading: -0.02, body: 0, caps: 0.04 },
242
+ /** Line height, as a multiple of the font size. */
243
+ leading: { display: 1.1, heading: 1.3, body: 1.6 },
244
+ /** Control height, padding, font size and row padding per density. */
245
+ density: {
246
+ compact: { control: 30, pad: 10, fontSize: 13, rowPad: 10 },
247
+ comfortable: { control: 36, pad: 14, fontSize: 14, rowPad: 14 },
248
+ spacious: { control: 44, pad: 18, fontSize: 15, rowPad: 18 },
249
+ },
250
+ icon: 16,
251
+ focusOffset: 3,
252
+ /** The minimum hit size on touch screens. */
253
+ touchTarget: 44,
254
+ /** The opacity of the black scrim behind sheets and dialogs. */
255
+ scrimOpacity: 0.5,
256
+ } as const;