@crossworks/share-ui 0.300.143 → 0.400.1

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,264 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * Runs a Present canvas live in a sandboxed iframe (docs/proposals/
5
+ * canvas-files.md section 5.2). Like AppSandbox (./app-sandbox.tsx), the
6
+ * iframe NAVIGATES to a brain-rendered frame document, after this parent
7
+ * mints a seconds-lived ticket for it (the sandboxed navigation can carry no
8
+ * credential). Unlike an app there is no bridge: the frame may post `ready`
9
+ * and `error`, and this parent posts `theme`. Nothing else crosses.
10
+ *
11
+ * The iframe is `sandbox="allow-scripts"` only: an opaque origin, no
12
+ * cookies, no storage, no forms, no popups, no top navigation. The frame's
13
+ * own CSP header closes its network. A sandboxed frame may still navigate
14
+ * ITSELF, so the frame is shown only after it proves it is the document the
15
+ * brain served: its `ready` carries the nonce the ticket came with, which
16
+ * only the frame's prelude holds. A load with no proof, any load after the
17
+ * proof, or no proof within 20 seconds takes the frame down. The iframe also
18
+ * requires its CSP of whatever loads in it (`csp`, Chromium). The request
19
+ * of such a navigation still leaves a browser (no CSP directive stops it,
20
+ * and the Navigation API does not fire for an opaque frame's navigations);
21
+ * the desktop app refuses it before it leaves (will-frame-navigate).
22
+ *
23
+ * Replay: bump `reloadKey`; a new ticket is minted and the frame reloads, so
24
+ * an animation starts again from its first frame. Full screen: the host
25
+ * calls `requestFullscreen()` on the element `frameRef` hands back.
26
+ */
27
+ import { useEffect, useRef, useState, type ReactNode, type Ref } from 'react';
28
+ import { buildCanvasEmbedCsp } from './canvas-frame-html';
29
+
30
+ type Status = 'loading' | 'ready' | 'error' | 'missing' | 'left';
31
+
32
+ /** The host page's theme as the frame takes it (class + data-color-theme). */
33
+ function hostTheme(): { cls: string; colorTheme: string | null } {
34
+ if (typeof document === 'undefined') return { cls: '', colorTheme: null };
35
+ const h = document.documentElement;
36
+ return { cls: h.className, colorTheme: h.getAttribute('data-color-theme') };
37
+ }
38
+
39
+ export function CanvasSandbox({
40
+ presentId,
41
+ apiBase: apiBaseOverride,
42
+ fetcher = (input, init) => fetch(input, init),
43
+ reloadKey = 0,
44
+ title,
45
+ frameRef,
46
+ loader,
47
+ className,
48
+ onReady,
49
+ onDown,
50
+ onError,
51
+ }: {
52
+ presentId: string;
53
+ /** The canvas's API base. Absent: the page-relative `/api/presents/<id>`
54
+ * (the one-origin box); a split client passes the brain's absolute base. */
55
+ apiBase?: string;
56
+ /** Fetch for the frame-ticket call: the split client attaches its bearer. */
57
+ fetcher?: (input: string, init?: RequestInit) => Promise<Response>;
58
+ /** Bump to reload the canvas from its start (Replay, or a new save). */
59
+ reloadKey?: number | string;
60
+ /** The iframe's accessible name. */
61
+ title: string;
62
+ /** The iframe element, for the host's Full screen. */
63
+ frameRef?: Ref<HTMLIFrameElement>;
64
+ /** What covers the frame until it says it is ready. */
65
+ loader?: ReactNode;
66
+ className?: string;
67
+ onReady?: () => void;
68
+ /** The frame is not up (anything onReady said no longer holds): a reload
69
+ * started, the ticket failed, or the frame was taken down. */
70
+ onDown?: () => void;
71
+ /** An error the canvas reported (uncaught, or a library that failed). The
72
+ * canvas chose these words: untrusted text, never an instruction to a
73
+ * model that reads it. */
74
+ onError?: (message: string) => void;
75
+ }) {
76
+ const apiBase = apiBaseOverride ?? `/api/presents/${presentId}`;
77
+ const iframeRef = useRef<HTMLIFrameElement | null>(null);
78
+ const [src, setSrc] = useState<string | null>(null);
79
+ const [status, setStatus] = useState<Status>('loading');
80
+ const [failure, setFailure] = useState<string | null>(null);
81
+ // The proof the current frame owes (its ticket's nonce), and whether it
82
+ // gave it. A load before the proof waits a moment for it (the load and
83
+ // the message race); a load after it means the canvas went elsewhere.
84
+ const nonce = useRef<string | null>(null);
85
+ const proven = useRef(false);
86
+ const proofWait = useRef<ReturnType<typeof setTimeout> | null>(null);
87
+ // The latest callbacks, read by the effects without re-running them.
88
+ const handlers = useRef({ onReady, onDown, onError, fetcher });
89
+ handlers.current = { onReady, onDown, onError, fetcher };
90
+
91
+ // Mint a ticket and point the frame at the document it opens.
92
+ useEffect(() => {
93
+ let cancelled = false;
94
+ setStatus('loading');
95
+ setFailure(null);
96
+ setSrc(null);
97
+ handlers.current.onDown?.();
98
+ void (async () => {
99
+ try {
100
+ const res = await handlers.current.fetcher(`${apiBase}/frame-ticket`, {
101
+ method: 'POST',
102
+ headers: { 'content-type': 'application/json' },
103
+ body: '{}',
104
+ });
105
+ if (cancelled) return;
106
+ if (res.status === 404) {
107
+ setStatus('missing');
108
+ return;
109
+ }
110
+ if (!res.ok) throw new Error(`frame ticket: ${res.status}`);
111
+ const { ticket, nonce: n } = (await res.json()) as { ticket: string; nonce?: string };
112
+ if (cancelled) return;
113
+ nonce.current = typeof n === 'string' && n ? n : null;
114
+ proven.current = false;
115
+ const { cls, colorTheme } = hostTheme();
116
+ const qs = new URLSearchParams({ t: ticket, cls });
117
+ if (colorTheme) qs.set('ct', colorTheme);
118
+ setSrc(`${apiBase}/frame?${qs.toString()}`);
119
+ } catch {
120
+ if (!cancelled) setStatus('error');
121
+ }
122
+ })();
123
+ return () => {
124
+ cancelled = true;
125
+ };
126
+ }, [apiBase, reloadKey]);
127
+
128
+ // Take the frame down: whatever it shows now is not the canvas.
129
+ const takeDown = (why: string) => {
130
+ if (proofWait.current) clearTimeout(proofWait.current);
131
+ proofWait.current = null;
132
+ setSrc(null);
133
+ setStatus('left');
134
+ handlers.current.onDown?.();
135
+ handlers.current.onError?.(why);
136
+ };
137
+
138
+ // A frame that never proves itself (a page the canvas navigated to that
139
+ // never finishes loading, or a canvas whose script blocks its load) is
140
+ // taken down, never uncovered.
141
+ useEffect(() => {
142
+ if (!src) return;
143
+ const t = setTimeout(() => {
144
+ if (!proven.current) takeDown('the canvas did not start');
145
+ }, 20_000);
146
+ return () => clearTimeout(t);
147
+ }, [src]);
148
+
149
+ // The frame's two messages, from this frame only.
150
+ useEffect(() => {
151
+ function onMessage(e: MessageEvent) {
152
+ const frame = iframeRef.current;
153
+ if (!frame || e.source !== frame.contentWindow) return;
154
+ const m = e.data as { v?: number; kind?: string; message?: unknown; n?: unknown } | null;
155
+ if (!m || m.v !== 1) return;
156
+ if (m.kind === 'ready') {
157
+ // Only the document the brain served knows the nonce.
158
+ if (!nonce.current || m.n !== nonce.current || proven.current) return;
159
+ proven.current = true;
160
+ if (proofWait.current) clearTimeout(proofWait.current);
161
+ proofWait.current = null;
162
+ setStatus('ready');
163
+ handlers.current.onReady?.();
164
+ } else if (m.kind === 'error') {
165
+ const text = typeof m.message === 'string' ? m.message.slice(0, 500) : 'the canvas failed';
166
+ setFailure(text);
167
+ handlers.current.onError?.(text);
168
+ }
169
+ }
170
+ window.addEventListener('message', onMessage);
171
+ return () => window.removeEventListener('message', onMessage);
172
+ }, []);
173
+
174
+ // Follow the host's theme while the canvas runs.
175
+ useEffect(() => {
176
+ if (typeof MutationObserver === 'undefined') return;
177
+ const post = () => {
178
+ const { cls, colorTheme } = hostTheme();
179
+ iframeRef.current?.contentWindow?.postMessage({ v: 1, kind: 'theme', cls, colorTheme }, '*');
180
+ };
181
+ const obs = new MutationObserver(post);
182
+ obs.observe(document.documentElement, {
183
+ attributes: true,
184
+ attributeFilter: ['class', 'data-color-theme'],
185
+ });
186
+ return () => obs.disconnect();
187
+ }, []);
188
+
189
+ const onFrameLoad = () => {
190
+ // After the proof, any load is another page.
191
+ if (proven.current) {
192
+ takeDown('the canvas tried to open another page');
193
+ return;
194
+ }
195
+ // Before it, the proof may still be on its way: give it a moment.
196
+ if (proofWait.current) return;
197
+ proofWait.current = setTimeout(() => {
198
+ proofWait.current = null;
199
+ if (!proven.current) takeDown('the canvas tried to open another page');
200
+ }, 1_500);
201
+ };
202
+
203
+ useEffect(
204
+ () => () => {
205
+ if (proofWait.current) clearTimeout(proofWait.current);
206
+ },
207
+ [],
208
+ );
209
+
210
+ // The origin of the canvas API, for the CSP the iframe requires.
211
+ const apiOrigin =
212
+ typeof window === 'undefined' ? '' : new URL(apiBase, window.location.href).origin;
213
+
214
+ const setFrame = (el: HTMLIFrameElement | null) => {
215
+ iframeRef.current = el;
216
+ if (typeof frameRef === 'function') frameRef(el);
217
+ else if (frameRef) (frameRef as { current: HTMLIFrameElement | null }).current = el;
218
+ };
219
+
220
+ return (
221
+ <div className={['relative h-full w-full', className].filter(Boolean).join(' ')}>
222
+ {src ? (
223
+ <iframe
224
+ ref={setFrame}
225
+ key={src}
226
+ src={src}
227
+ title={title}
228
+ sandbox="allow-scripts"
229
+ {...{ csp: buildCanvasEmbedCsp(apiOrigin) }}
230
+ referrerPolicy="no-referrer"
231
+ onLoad={onFrameLoad}
232
+ className="absolute inset-0 h-full w-full border-0 bg-background"
233
+ />
234
+ ) : null}
235
+ {status === 'loading' && failure ? (
236
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 bg-background px-6 text-center">
237
+ <p className="text-sm text-muted-foreground">The canvas failed to start.</p>
238
+ {/* The canvas's own words, labelled as such: it chose them. */}
239
+ <p className="max-w-prose text-xs text-muted-foreground">
240
+ Reported by the canvas: {failure.slice(0, 200)}
241
+ </p>
242
+ </div>
243
+ ) : status === 'loading' ? (
244
+ <div className="absolute inset-0 flex items-center justify-center bg-background">
245
+ {loader ?? <p className="text-sm text-muted-foreground">Loading…</p>}
246
+ </div>
247
+ ) : status === 'missing' ? (
248
+ <div className="absolute inset-0 flex items-center justify-center bg-background">
249
+ <p className="text-sm text-muted-foreground">This canvas is not available.</p>
250
+ </div>
251
+ ) : status === 'left' ? (
252
+ <div className="absolute inset-0 flex items-center justify-center bg-background px-6 text-center">
253
+ <p className="text-sm text-muted-foreground">
254
+ The canvas tried to open another page, so it was stopped. Replay to run it again.
255
+ </p>
256
+ </div>
257
+ ) : status === 'error' ? (
258
+ <div className="absolute inset-0 flex items-center justify-center bg-background">
259
+ <p className="text-sm text-muted-foreground">The canvas could not be loaded.</p>
260
+ </div>
261
+ ) : null}
262
+ </div>
263
+ );
264
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Colour plumbing for Drift: CSS colour → linear sRGB → OKLab, the space the
3
+ * shader blends in.
4
+ *
5
+ * Why OKLab: an sRGB lerp between two saturated colours sags through a muddy,
6
+ * darker midpoint (blue → orange crosses grey). OKLab is perceptually uniform,
7
+ * so a blend keeps its lightness and chroma and the gradient reads luminous
8
+ * rather than dirty. It is the single biggest visual difference from Neat.
9
+ */
10
+
11
+ export type Rgb = [number, number, number];
12
+ export type Lab = [number, number, number];
13
+
14
+ /** Parse #rgb / #rrggbb / #rrggbbaa / rgb() / rgba(). Null on anything else. */
15
+ export function parseHexOrRgb(input: string): Rgb | null {
16
+ const t = input.trim().toLowerCase();
17
+ // Shorthand MUST parse: minified stylesheets shorten tokens (#ffffff → #fff),
18
+ // and getComputedStyle hands back exactly that on deployed builds.
19
+ const short = /^#([0-9a-f]{3})$/.exec(t)?.[1];
20
+ if (short) {
21
+ const c = (i: number) => parseInt(short.charAt(i) + short.charAt(i), 16);
22
+ return [c(0), c(1), c(2)];
23
+ }
24
+ const long = /^#([0-9a-f]{6})(?:[0-9a-f]{2})?$/.exec(t)?.[1];
25
+ if (long) {
26
+ const n = parseInt(long, 16);
27
+ return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];
28
+ }
29
+ const fn = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(t);
30
+ if (fn) return [Number(fn[1]), Number(fn[2]), Number(fn[3])];
31
+ return null;
32
+ }
33
+
34
+ let probe: CanvasRenderingContext2D | null | undefined;
35
+
36
+ /**
37
+ * Any CSS colour (oklch(), hsl(), named…) → sRGB bytes. Hex and rgb() take the
38
+ * fast path; the rest are normalised by a 1×1 2D canvas, which speaks every
39
+ * colour syntax the browser does. Null when the string is not a colour.
40
+ */
41
+ export function parseColor(input: string): Rgb | null {
42
+ const fast = parseHexOrRgb(input);
43
+ if (fast) return fast;
44
+ if (typeof document === 'undefined') return null;
45
+ if (probe === undefined) {
46
+ probe = document.createElement('canvas').getContext('2d', { willReadFrequently: true });
47
+ }
48
+ if (!probe) return null;
49
+ // A sentinel first, so an unparseable string (which leaves fillStyle alone)
50
+ // is detected instead of returning the previous colour.
51
+ probe.fillStyle = '#010203';
52
+ probe.fillStyle = input;
53
+ if (probe.fillStyle === '#010203' && !/^#010203$/i.test(input.trim())) return null;
54
+ probe.clearRect(0, 0, 1, 1);
55
+ probe.fillRect(0, 0, 1, 1);
56
+ const d = probe.getImageData(0, 0, 1, 1).data;
57
+ return [d[0] ?? 0, d[1] ?? 0, d[2] ?? 0];
58
+ }
59
+
60
+ const toLinear = (c: number) => {
61
+ const v = c / 255;
62
+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
63
+ };
64
+
65
+ const fromLinear = (v: number) => {
66
+ const c = v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;
67
+ return Math.max(0, Math.min(255, Math.round(c * 255)));
68
+ };
69
+
70
+ /** sRGB bytes → OKLab (Björn Ottosson's published matrices). */
71
+ export function rgbToOklab([r8, g8, b8]: Rgb): Lab {
72
+ const r = toLinear(r8);
73
+ const g = toLinear(g8);
74
+ const b = toLinear(b8);
75
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
76
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
77
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
78
+ return [
79
+ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
80
+ 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
81
+ 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
82
+ ];
83
+ }
84
+
85
+ /** OKLab → sRGB bytes, gamut-clipped. */
86
+ export function oklabToRgb([L, a, b]: Lab): Rgb {
87
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
88
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
89
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
90
+ return [
91
+ fromLinear(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
92
+ fromLinear(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
93
+ fromLinear(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
94
+ ];
95
+ }
96
+
97
+ export function rgbToHex([r, g, b]: Rgb): string {
98
+ const c = (v: number) =>
99
+ Math.max(0, Math.min(255, Math.round(v)))
100
+ .toString(16)
101
+ .padStart(2, '0');
102
+ return `#${c(r)}${c(g)}${c(b)}`;
103
+ }
104
+
105
+ /** OKLab mix: 0 keeps `from`, 1 lands on `to`. */
106
+ export function mixLab(from: Lab, to: Lab, t: number): Lab {
107
+ return [
108
+ from[0] + (to[0] - from[0]) * t,
109
+ from[1] + (to[1] - from[1]) * t,
110
+ from[2] + (to[2] - from[2]) * t,
111
+ ];
112
+ }
@@ -0,0 +1,243 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { oklabToRgb, parseHexOrRgb, rgbToOklab } from './color';
3
+ import { DRIFT_STYLE_RESOLUTION, normalizeDriftOptions } from './options';
4
+ import {
5
+ DRIFT_SPEC_MAX,
6
+ decodeDriftSpec,
7
+ driftOptionsFromSpec,
8
+ encodeDriftSpec,
9
+ randomDriftSpec,
10
+ readDriftSurface,
11
+ type DriftSpec,
12
+ } from './spec';
13
+ import { contrastRatio, driftPaletteFromTheme, type DriftThemeTokens } from './theme';
14
+
15
+ const TOKENS: DriftThemeTokens = {
16
+ background: '#fff',
17
+ primary: '#3b5bdb',
18
+ accent: '#7048e8',
19
+ secondary: '#0ca678',
20
+ chart: ['#666ed1', '#d08300', '#2f9e44', '#e03131', '#1c7ed6'],
21
+ };
22
+
23
+ // The default (jackdaw) theme's own tokens (styles/themes.css).
24
+ const JACKDAW_LIGHT: DriftThemeTokens = {
25
+ background: '#faedcf',
26
+ mutedForeground: '#6a4f30',
27
+ primary: '#b23a06',
28
+ accent: '#f0c88c',
29
+ secondary: '#f0c88c',
30
+ chart: ['#e46e08', '#eb9f13', '#c83c04', '#5c1e02', '#baae94'],
31
+ };
32
+ const JACKDAW: Array<[DriftThemeTokens, 'light' | 'dark']> = [
33
+ [JACKDAW_LIGHT, 'light'],
34
+ [
35
+ {
36
+ background: '#120f0e',
37
+ mutedForeground: '#bda882',
38
+ primary: '#eb9f13',
39
+ accent: '#2d241d',
40
+ secondary: '#2d241d',
41
+ chart: ['#eb9f13', '#e46e08', '#f0c88c', '#c83c04', '#baae94'],
42
+ },
43
+ 'dark',
44
+ ],
45
+ ];
46
+
47
+ describe('color', () => {
48
+ it('parses minified shorthand hex — what deployed stylesheets hand back', () => {
49
+ expect(parseHexOrRgb('#fff')).toEqual([255, 255, 255]);
50
+ expect(parseHexOrRgb('#eeeeee')).toEqual([238, 238, 238]);
51
+ expect(parseHexOrRgb('rgb(1, 2, 3)')).toEqual([1, 2, 3]);
52
+ expect(parseHexOrRgb('nope')).toBeNull();
53
+ });
54
+
55
+ it('round-trips sRGB through OKLab', () => {
56
+ for (const rgb of [
57
+ [0, 0, 0],
58
+ [255, 255, 255],
59
+ [59, 91, 219],
60
+ [240, 140, 0],
61
+ ] as const) {
62
+ expect(oklabToRgb(rgbToOklab([...rgb]))).toEqual([...rgb]);
63
+ }
64
+ });
65
+ });
66
+
67
+ describe('spec', () => {
68
+ it('round-trips and encodes canonically', () => {
69
+ const spec = randomDriftSpec({ style: 'aurora', warp: 0.333333 });
70
+ const encoded = encodeDriftSpec(spec);
71
+ expect(decodeDriftSpec(encoded)).toEqual({ ...spec, warp: 0.33 });
72
+ expect(encodeDriftSpec(decodeDriftSpec(encoded)!)).toBe(encoded);
73
+ });
74
+
75
+ it('keeps the largest spec under the storage cap', () => {
76
+ const worst: DriftSpec = {
77
+ v: 2,
78
+ seed: 0xffffffff,
79
+ tone: 'lighter',
80
+ speed: 5.55,
81
+ style: 'marble',
82
+ pal: 'chart',
83
+ str: 0.55,
84
+ scale: 3.33,
85
+ warp: 0.55,
86
+ soft: 0.55,
87
+ light: 0.55,
88
+ grain: 0.55,
89
+ angle: -179,
90
+ };
91
+ expect(encodeDriftSpec(worst).length).toBeLessThan(DRIFT_SPEC_MAX);
92
+ });
93
+
94
+ it('upgrades a saved Neat v1 spec to silk, keeping seed, tone and speed', () => {
95
+ expect(decodeDriftSpec('{"v":1,"seed":55361,"tone":"darker","speed":3}')).toMatchObject({
96
+ v: 2,
97
+ seed: 55361,
98
+ tone: 'darker',
99
+ speed: 3,
100
+ style: 'silk',
101
+ });
102
+ });
103
+
104
+ it('rejects garbage and clamps out-of-range numbers', () => {
105
+ expect(decodeDriftSpec('')).toBeNull();
106
+ expect(decodeDriftSpec('{')).toBeNull();
107
+ expect(decodeDriftSpec('{"v":3,"seed":1}')).toBeNull();
108
+ expect(decodeDriftSpec('{"v":2,"seed":-1}')).toBeNull();
109
+ expect(decodeDriftSpec('{"v":1,"seed":1,"tone":"loud","speed":1}')).toBeNull();
110
+ expect(decodeDriftSpec('{"v":2,"seed":1,"warp":9,"style":"blob"}')).toMatchObject({
111
+ warp: 1,
112
+ style: 'mesh',
113
+ });
114
+ });
115
+ });
116
+
117
+ describe('theme palette', () => {
118
+ const base = { seed: 7, tone: 'auto' as const, mode: 'light' as const, source: 'brand' as const };
119
+
120
+ it('is deterministic per seed', () => {
121
+ expect(driftPaletteFromTheme(TOKENS, { ...base, strength: 0.5 })).toEqual(
122
+ driftPaletteFromTheme(TOKENS, { ...base, strength: 0.5 }),
123
+ );
124
+ });
125
+
126
+ it('washes toward the page surface as strength falls', () => {
127
+ const chroma = (hex: string) => {
128
+ const [, a, b] = rgbToOklab(parseHexOrRgb(hex)!);
129
+ return Math.hypot(a, b);
130
+ };
131
+ const total = (strength: number) =>
132
+ driftPaletteFromTheme(TOKENS, { ...base, strength }).colors.reduce(
133
+ (s, c) => s + chroma(c),
134
+ 0,
135
+ );
136
+ expect(total(0.1)).toBeLessThan(total(0.5));
137
+ expect(total(0.5)).toBeLessThan(total(1));
138
+ });
139
+
140
+ it('uses the chart tokens when asked, plus the ground', () => {
141
+ const p = driftPaletteFromTheme(TOKENS, { ...base, strength: 1, source: 'chart' });
142
+ expect(p.colors).toHaveLength(TOKENS.chart.length + 1);
143
+ });
144
+
145
+ it('holds muted text at AA on the app surface, light and dark, at any strength', () => {
146
+ for (const [tokens, mode] of JACKDAW) {
147
+ const muted = parseHexOrRgb(tokens.mutedForeground!)!;
148
+ for (const str of [0, 0.55, 1])
149
+ for (const pal of ['brand', 'chart'] as const)
150
+ for (const tone of ['auto', 'darker', 'lighter'] as const)
151
+ for (let seed = 1; seed < 400; seed += 37) {
152
+ const spec = { ...decodeDriftSpec(`{"v":2,"seed":${seed}}`)!, str, pal, tone };
153
+ const o = driftOptionsFromSpec(spec, tokens, mode, 'app');
154
+ for (const c of [o.background!, ...(o.colors as string[])]) {
155
+ expect(contrastRatio(muted, parseHexOrRgb(c)!)).toBeGreaterThanOrEqual(4.5);
156
+ }
157
+ }
158
+ }
159
+ });
160
+
161
+ it('paints the public surface in full colour: no muted-text floor', () => {
162
+ for (const [tokens, mode] of JACKDAW)
163
+ for (let seed = 1; seed < 400; seed += 37) {
164
+ const spec = decodeDriftSpec(`{"v":2,"seed":${seed}}`)!;
165
+ const o = driftOptionsFromSpec(spec, tokens, mode, 'public');
166
+ // Exactly the palette the spec asks for, with no floor applied.
167
+ const raw = driftPaletteFromTheme(tokens, {
168
+ seed,
169
+ tone: spec.tone,
170
+ mode,
171
+ source: spec.pal,
172
+ strength: spec.str,
173
+ });
174
+ expect({ background: o.background, colors: o.colors }).toEqual(raw);
175
+ }
176
+ });
177
+
178
+ it('keeps colour strong on the default light theme in public, subtle in the app', () => {
179
+ // How far the boldest colour stands off the painted ground, in OKLab:
180
+ // the measure of "washed flat". Default spec (strength 0.55, brand).
181
+ const reach = (o: Partial<{ background: string; colors: unknown }>) => {
182
+ const ground = rgbToOklab(parseHexOrRgb(o.background!)!);
183
+ return Math.max(
184
+ ...(o.colors as string[]).map((c) => {
185
+ const [l, a, b] = rgbToOklab(parseHexOrRgb(c)!);
186
+ return Math.hypot(l - ground[0], a - ground[1], b - ground[2]);
187
+ }),
188
+ );
189
+ };
190
+ const pub: number[] = [];
191
+ const app: number[] = [];
192
+ for (let seed = 1; seed < 400; seed += 37) {
193
+ const spec = decodeDriftSpec(`{"v":2,"seed":${seed}}`)!;
194
+ pub.push(reach(driftOptionsFromSpec(spec, JACKDAW_LIGHT, 'light', 'public')));
195
+ app.push(reach(driftOptionsFromSpec(spec, JACKDAW_LIGHT, 'light', 'app')));
196
+ }
197
+ const mean = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / xs.length;
198
+ // Measured 2026-10-24 over these seeds: public 0.24 to 0.29 (mean 0.26),
199
+ // app 0.12 on every seed (the floor holds the primary back).
200
+ expect(Math.min(...pub)).toBeGreaterThan(0.22);
201
+ expect(Math.max(...app)).toBeLessThan(0.13);
202
+ expect(mean(pub)).toBeGreaterThan(2 * mean(app));
203
+ });
204
+
205
+ it('reads a surface off markup, never dropping the floor by accident', () => {
206
+ expect(readDriftSurface('public')).toBe('public');
207
+ for (const raw of ['app', '', 'PUBLIC', ' public', 'full', null, undefined])
208
+ expect(readDriftSurface(raw)).toBe('app');
209
+ });
210
+
211
+ it('holds the floor for any surface but the exact public, also from untyped callers', () => {
212
+ const spec = decodeDriftSpec('{"v":2,"seed":5,"str":1}')!;
213
+ const floored = driftOptionsFromSpec(spec, JACKDAW_LIGHT, 'light', 'app');
214
+ for (const raw of [undefined, null, '', 'App', 'PUBLIC', { pointer: 0.6 }]) {
215
+ const o = driftOptionsFromSpec(spec, JACKDAW_LIGHT, 'light', raw as unknown as 'app');
216
+ expect({ background: o.background, colors: o.colors }).toEqual({
217
+ background: floored.background,
218
+ colors: floored.colors,
219
+ });
220
+ }
221
+ });
222
+
223
+ it('maps a spec onto engine options', () => {
224
+ const spec = { ...decodeDriftSpec('{"v":2,"seed":9,"speed":4,"style":"dunes"}')! };
225
+ const o = driftOptionsFromSpec(spec, TOKENS, 'dark', 'app');
226
+ expect(o.style).toBe('dunes');
227
+ expect(o.speed).toBe(2);
228
+ expect(o.colors?.length).toBe(4);
229
+ });
230
+ });
231
+
232
+ describe('options', () => {
233
+ it('fills defaults, clamps, and leaves resolution 0 to mean per-style', () => {
234
+ const o = normalizeDriftOptions({ warp: 5, colors: [], resolution: 0 });
235
+ expect(o.warp).toBe(1);
236
+ // An explicit empty list stays empty (the engine then paints nothing);
237
+ // only an omitted one takes the defaults.
238
+ expect(o.colors.length).toBe(0);
239
+ expect(normalizeDriftOptions({}).colors.length).toBeGreaterThan(0);
240
+ expect(o.resolution).toBe(0);
241
+ expect(DRIFT_STYLE_RESOLUTION.mesh).toBeLessThan(DRIFT_STYLE_RESOLUTION.silk);
242
+ });
243
+ });