@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.
package/src/image.tsx ADDED
@@ -0,0 +1,79 @@
1
+ // Images the kit renders from data (covers, product photos, avatars, logos),
2
+ // with a one-shot fallback when the image fails. Internal: not exported.
3
+ import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
4
+ import { ImageMissing } from "./icons.js";
5
+
6
+ /** Optional fallbacks on an image a component renders from data. */
7
+ export interface ImageFallback {
8
+ /** Shown once if `src` fails or is empty. Not retried if it fails too. */
9
+ fallbackSrc?: string;
10
+ /**
11
+ * Shown when every image fails, in the image's reserved box, instead of the
12
+ * default placeholder icon. It is visual only: the image's `alt` names it.
13
+ */
14
+ fallback?: ReactNode;
15
+ }
16
+
17
+ /**
18
+ * Which source to show: `src`, then `fallbackSrc` once, then none. Each step
19
+ * happens at most once per `src`, so a failing fallback can't loop, and a new
20
+ * `src` starts over. An error that fired before hydration attached `onError`
21
+ * is caught on mount from the image's own state.
22
+ */
23
+ export function useImageFallback(src: string, fallbackSrc?: string) {
24
+ const [failed, setFailed] = useState<{ src: string; stage: 1 | 2 } | null>(
25
+ null,
26
+ );
27
+ const second = fallbackSrc && fallbackSrc !== src ? fallbackSrc : undefined;
28
+ let stage = failed?.src === src ? failed.stage : 0;
29
+ if (stage === 0 && !src) stage = second ? 1 : 2;
30
+ if (stage === 1 && !second) stage = 2;
31
+ const current = stage === 0 ? src : stage === 1 ? second : undefined;
32
+ const fail = () => setFailed({ src, stage: stage === 0 && second ? 1 : 2 });
33
+ const ref = useRef<HTMLImageElement>(null);
34
+ useLayoutEffect(() => {
35
+ const img = ref.current;
36
+ if (img?.complete && img.naturalWidth === 0 && img.getAttribute("src"))
37
+ fail();
38
+ // `fail` reads this render's stage; re-run only when the source changes.
39
+ // eslint-disable-next-line react-hooks/exhaustive-deps
40
+ }, [current]);
41
+ return { current, ref, onError: fail };
42
+ }
43
+
44
+ /**
45
+ * An image with the kit's fallback: `fallbackSrc` once, then `fallback` or a
46
+ * placeholder icon in the same reserved box (the container sets the size), so
47
+ * nothing shifts. The placeholder carries the image's accessible name.
48
+ */
49
+ export function KitImage({
50
+ src,
51
+ alt,
52
+ fallbackSrc,
53
+ fallback,
54
+ loading,
55
+ }: ImageFallback & {
56
+ src: string;
57
+ alt: string;
58
+ loading?: "lazy";
59
+ }) {
60
+ const image = useImageFallback(src, fallbackSrc);
61
+ if (image.current)
62
+ return (
63
+ <img
64
+ ref={image.ref}
65
+ src={image.current}
66
+ alt={alt}
67
+ loading={loading}
68
+ onError={image.onError}
69
+ />
70
+ );
71
+ return (
72
+ <span
73
+ className="m-image-fallback"
74
+ {...(alt ? { role: "img", "aria-label": alt } : { "aria-hidden": true })}
75
+ >
76
+ {fallback ? <span aria-hidden="true">{fallback}</span> : <ImageMissing />}
77
+ </span>
78
+ );
79
+ }
package/src/marketing.tsx CHANGED
@@ -1,3 +1,4 @@
1
+ import { useImageFallback } from "./image.js";
1
2
  import {
2
3
  IconLinks,
3
4
  KitLink,
@@ -545,6 +546,15 @@ export function Testimonial({
545
546
  </figure>
546
547
  );
547
548
  }
549
+ /** A logo, or its name as text when there is no image or it fails to load. */
550
+ function Logo({ name, image }: { name: string; image?: string }) {
551
+ const logo = useImageFallback(image ?? "");
552
+ return logo.current ? (
553
+ <img ref={logo.ref} src={logo.current} alt={name} onError={logo.onError} />
554
+ ) : (
555
+ <span>{name}</span>
556
+ );
557
+ }
548
558
  export function LogoCloud({
549
559
  id,
550
560
  className,
@@ -576,11 +586,7 @@ export function LogoCloud({
576
586
  <ul>
577
587
  {items.map((item) => (
578
588
  <li key={item.name}>
579
- {item.image ? (
580
- <img src={item.image} alt={item.name} />
581
- ) : (
582
- <span>{item.name}</span>
583
- )}
589
+ <Logo name={item.name} image={item.image} />
584
590
  </li>
585
591
  ))}
586
592
  </ul>
@@ -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;