@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,152 @@
1
+ import { mixLab, oklabToRgb, parseColor, rgbToHex, rgbToOklab, type Lab, type Rgb } from './color';
2
+ import { mulberry32 } from './options';
3
+ import type { DriftPaletteSource, DriftTone } from '@mantle/content-core/drift-spec';
4
+
5
+ export type { DriftPaletteSource, DriftTone };
6
+
7
+ /**
8
+ * Theme → Drift palette. A saved background stores NO colours: every colour
9
+ * is derived from the live theme tokens at paint time, so one background
10
+ * follows all the colour themes and light/dark by construction (the contract
11
+ * the Neat spec established, kept).
12
+ *
13
+ * The derived colours are washes — each brand colour pulled part of the way
14
+ * into `--background` — and `strength` says how far. That is the legibility
15
+ * guarantee: at the default the gradient reads as a tint of the page
16
+ * surface, never a poster fighting the text on it. All of it happens in
17
+ * OKLab, so a wash keeps its hue instead of greying on the way to the ground.
18
+ */
19
+
20
+ export type DriftThemeTokens = {
21
+ background: string;
22
+ /** The quietest text that sits on the background; the legibility floor
23
+ * is measured against it. Absent: no floor (a test, a bare palette). */
24
+ mutedForeground?: string;
25
+ primary: string;
26
+ accent: string;
27
+ secondary: string;
28
+ chart: string[];
29
+ };
30
+
31
+ /** The tokens, resolved to literal colours off the live document. Null when
32
+ * the theme is unresolvable (a test DOM, a broken stylesheet) — paint
33
+ * nothing rather than a wrong guess. */
34
+ export function readDriftThemeTokens(
35
+ root: Element = document.documentElement,
36
+ ): DriftThemeTokens | null {
37
+ const cs = getComputedStyle(root);
38
+ const read = (name: string) => cs.getPropertyValue(name).trim();
39
+ const tokens: DriftThemeTokens = {
40
+ background: read('--background'),
41
+ mutedForeground: read('--muted-foreground') || undefined,
42
+ primary: read('--primary'),
43
+ accent: read('--accent'),
44
+ secondary: read('--secondary'),
45
+ chart: [1, 2, 3, 4, 5].map((i) => read(`--chart-${i}`)).filter(Boolean),
46
+ };
47
+ return tokens.background && tokens.primary ? tokens : null;
48
+ }
49
+
50
+ export type DriftPaletteInput = {
51
+ seed: number;
52
+ tone: DriftTone;
53
+ mode: 'light' | 'dark';
54
+ source: DriftPaletteSource;
55
+ /** 0 = a whisper of colour on the page surface, 1 = the raw theme colours. */
56
+ strength: number;
57
+ /** Minimum contrast (WCAG ratio) of `tokens.mutedForeground` against every
58
+ * colour painted; a colour below it is pulled toward the page surface
59
+ * until it passes. Omitted or no muted token: no floor. */
60
+ textFloor?: number;
61
+ };
62
+
63
+ /** The floor the 'app' surface paints with (see DriftSurface in spec.ts): AA
64
+ * for body text (4.5:1) on the palette, plus a margin for the shading and
65
+ * grain the shader adds on top. */
66
+ export const DRIFT_TEXT_FLOOR = 4.8;
67
+
68
+ function luminance([r, g, b]: Rgb): number {
69
+ const lin = (v: number) => {
70
+ const c = v / 255;
71
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
72
+ };
73
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
74
+ }
75
+
76
+ /** WCAG contrast ratio of two sRGB colours, 1 to 21. */
77
+ export function contrastRatio(a: Rgb, b: Rgb): number {
78
+ const x = luminance(a);
79
+ const y = luminance(b);
80
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
81
+ }
82
+
83
+ /** `lab` pulled toward `ground` just far enough that `text` reads on it at
84
+ * `floor`. When even the ground fails the floor (a theme's own problem),
85
+ * the ground is the best there is. */
86
+ function liftToFloor(lab: Lab, ground: Lab, text: Rgb, floor: number): Lab {
87
+ if (contrastRatio(text, oklabToRgb(lab)) >= floor) return lab;
88
+ if (contrastRatio(text, oklabToRgb(ground)) < floor) return ground;
89
+ let lo = 0;
90
+ let hi = 1;
91
+ for (let i = 0; i < 14; i++) {
92
+ const mid = (lo + hi) / 2;
93
+ if (contrastRatio(text, oklabToRgb(mixLab(lab, ground, mid))) >= floor) hi = mid;
94
+ else lo = mid;
95
+ }
96
+ return mixLab(lab, ground, hi);
97
+ }
98
+
99
+ /** Spec + live tokens → the background and colours Drift paints. Pure and
100
+ * deterministic: a preview and the real surface can never disagree. */
101
+ export function driftPaletteFromTheme(
102
+ tokens: DriftThemeTokens,
103
+ input: DriftPaletteInput,
104
+ ): { background: string; colors: string[] } {
105
+ const rnd = mulberry32(input.seed ^ 0x5bd1e995);
106
+ const bgRgb = parseColor(tokens.background);
107
+ if (!bgRgb) return { background: tokens.background, colors: [] };
108
+ const bg = rgbToOklab(bgRgb);
109
+ const darker = input.tone === 'darker' || (input.tone === 'auto' && input.mode === 'dark');
110
+ const strength = Math.min(1, Math.max(0, input.strength));
111
+
112
+ const sources =
113
+ input.source === 'chart' && tokens.chart.length >= 2
114
+ ? tokens.chart
115
+ : [tokens.primary, tokens.accent, tokens.secondary];
116
+
117
+ // Seeded order, so re-rolling the seed reshuffles which hue leads.
118
+ const order = sources.map((c, i) => ({ c, k: rnd() + i * 0.01 })).sort((a, b) => a.k - b.k);
119
+
120
+ // The ground shifts a touch off the page surface in the chosen direction,
121
+ // so the darkest (or lightest) parts sit just beyond the content's own.
122
+ const shift = (lab: Lab, amount: number): Lab => [
123
+ Math.min(1, Math.max(0, lab[0] + (darker ? -amount : amount))),
124
+ lab[1],
125
+ lab[2],
126
+ ];
127
+
128
+ // The legibility floor: every colour painted keeps the quietest text
129
+ // readable, whatever the strength, tone or theme asked for.
130
+ const text =
131
+ input.textFloor && tokens.mutedForeground ? parseColor(tokens.mutedForeground) : null;
132
+ const floor = (lab: Lab): Lab =>
133
+ text && input.textFloor ? liftToFloor(lab, bg, text, input.textFloor) : lab;
134
+
135
+ const colors: string[] = [];
136
+ for (const { c } of order) {
137
+ const rgb = parseColor(c);
138
+ if (!rgb) continue;
139
+ // Per-colour jitter keeps the washes from all landing at one distance.
140
+ const toward = (1 - strength) * (0.75 + rnd() * 0.25);
141
+ const washed = shift(mixLab(rgbToOklab(rgb), bg, toward), 0.03);
142
+ colors.push(rgbToHex(oklabToRgb(floor(washed))));
143
+ }
144
+ // The ground itself, once, so every style can open space between colours.
145
+ colors.splice(
146
+ Math.floor(rnd() * (colors.length + 1)),
147
+ 0,
148
+ rgbToHex(oklabToRgb(floor(shift(bg, 0.015)))),
149
+ );
150
+
151
+ return { background: rgbToHex(oklabToRgb(floor(shift(bg, 0.02)))), colors };
152
+ }
@@ -0,0 +1,77 @@
1
+ import type { DriftOptions } from './drift/options';
2
+ import { driftOptionsFromSpec, type DriftSpec, type DriftSurface } from './drift/spec';
3
+ import { readDriftThemeTokens } from './drift/theme';
4
+
5
+ // A plain-script host reads its surface off markup with this; re-exported
6
+ // here so the page bundle never imports the engine-carrying drift index.
7
+ export { readDriftSurface, type DriftSurface } from './drift/spec';
8
+
9
+ /**
10
+ * The one way a plain-script page puts a saved Drift spec onto a canvas: the
11
+ * /s reader and app frames (share-page.js). The owner app's React shell
12
+ * (DriftThemeBackdrop in the client) drives the same engine from the same
13
+ * `@mantle/share-ui/drift` modules, so a spec looks the same everywhere.
14
+ *
15
+ * - The engine is imported dynamically HERE, so the share-page bundle stays
16
+ * small and the WebGL code is a lazy chunk fetched only on brains that
17
+ * saved a background.
18
+ * - Colours are read off the live document per paint (shaders take
19
+ * literals, not `var()`); an unresolvable theme mounts NOTHING rather
20
+ * than a wrong guess, and the themed surface underneath is the fallback.
21
+ * - `prefers-reduced-motion` renders one still frame (the engine's
22
+ * `respectReducedMotion`, on by default); the wash still paints. Pointer
23
+ * lean stays off: it is a lab option, never a real surface's.
24
+ * - `surface` picks the look: 'app' holds the legibility floor (muted text
25
+ * at AA), 'public' paints full colour under pages that keep their text
26
+ * off the gradient; see DriftSurface in drift/spec.ts.
27
+ * - A mode or theme change is `repaint`: new colours as uniform writes on
28
+ * the same context, never a teardown.
29
+ *
30
+ * TIMING is the caller's job: mount and repaint only after the document's
31
+ * theme class has settled (in practice, from a requestAnimationFrame
32
+ * callback), or the tokens read belong to the OUTGOING theme. So is
33
+ * CANCELLATION: mount resolves after an await, so a caller that has moved on
34
+ * must destroy the returned handle instead of keeping it.
35
+ */
36
+
37
+ export type DriftMountHandle = {
38
+ /** Re-read the theme tokens and repaint in `mode`. */
39
+ repaint: (mode: 'light' | 'dark') => void;
40
+ destroy: () => void;
41
+ };
42
+
43
+ /**
44
+ * Build the background onto `canvas`. Resolves to a handle, or null when
45
+ * nothing mounted (unresolvable theme, no WebGL); null is the designed
46
+ * fallback, never an error.
47
+ */
48
+ export async function mountDrift(
49
+ canvas: HTMLCanvasElement,
50
+ spec: DriftSpec,
51
+ mode: 'light' | 'dark',
52
+ surface: DriftSurface,
53
+ overrides: Partial<DriftOptions> = {},
54
+ ): Promise<DriftMountHandle | null> {
55
+ const { createDrift } = await import('./drift/engine');
56
+ const tokens = readDriftThemeTokens();
57
+ if (!tokens) return null;
58
+ const options = driftOptionsFromSpec(spec, tokens, mode, surface);
59
+ // A theme whose colours did not parse paints NOTHING, not a guessed palette.
60
+ if (!options.colors || options.colors.length === 0) return null;
61
+ let engine: ReturnType<typeof createDrift>;
62
+ try {
63
+ engine = createDrift(canvas, { ...options, ...overrides });
64
+ } catch {
65
+ return null;
66
+ }
67
+ if (!engine) return null;
68
+ const handle = engine;
69
+ return {
70
+ repaint(next) {
71
+ const fresh = readDriftThemeTokens();
72
+ if (fresh)
73
+ handle.update({ ...driftOptionsFromSpec(spec, fresh, next, surface), ...overrides });
74
+ },
75
+ destroy: () => handle.destroy(),
76
+ };
77
+ }
@@ -18,6 +18,7 @@ const ROUTE_TOPICS: ReadonlyArray<readonly [route: string, topic: string]> = [
18
18
  ['/tables', 'tables'],
19
19
  ['/pages', 'pages'],
20
20
  ['/recall', 'recall'],
21
+ ['/present', 'present'],
21
22
  ['/draw', 'draw'],
22
23
  ['/notes', 'notes'],
23
24
  ['/files', 'files'],
package/src/nav-items.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  NotebookPen,
38
38
  Palette,
39
39
  PenTool,
40
+ Presentation,
40
41
  Radio,
41
42
  ScrollText,
42
43
  MessagesSquare,
@@ -112,6 +113,7 @@ export const NAV_GROUPS: NavGroup[] = [
112
113
  { name: 'Pages', href: '/pages', icon: BookText },
113
114
  { name: 'Recall', href: '/recall', icon: Map },
114
115
  { name: 'Draw', href: '/draw', icon: PenTool },
116
+ { name: 'Present', href: '/present', icon: Presentation },
115
117
  { name: 'Tables', href: '/tables', icon: Table2 },
116
118
  { name: 'Formulas', href: '/formulas', icon: Sigma },
117
119
  { name: 'Apps', href: '/apps', icon: AppWindow },
@@ -52,3 +52,23 @@ describe('NotePresenter: media: and draw: references', () => {
52
52
  expect(bare).not.toMatch(/<img[^>]*src="[^"]*(?:11111111|22222222)/);
53
53
  });
54
54
  });
55
+
56
+ describe('NotePresenter: present: canvases', () => {
57
+ const CANVAS = '33333333-3333-4333-8333-333333333333';
58
+ const OTHER = '44444444-4444-4444-8444-444444444444';
59
+ const md = `![Pump deck](present:${CANVAS})\n\n![Private plan](present:${OTHER})`;
60
+ const html = renderToStaticMarkup(
61
+ createElement(NotePresenter, {
62
+ view: { title: 'n', content: md },
63
+ chrome: 'embedded',
64
+ presentUrl: (id: string) => (id === CANVAS ? `/s/tok/present/${id}` : null),
65
+ }),
66
+ );
67
+
68
+ it('shows a canvas this surface serves, and a bare placeholder for any other', () => {
69
+ expect(html).toContain(`<img src="/s/tok/present/${CANVAS}" alt="Pump deck"/>`);
70
+ expect(html).toContain('[canvas]');
71
+ expect(html).not.toContain('Private plan');
72
+ expect(html).not.toContain(OTHER);
73
+ });
74
+ });
@@ -1,13 +1,13 @@
1
1
  import ReactMarkdown, { defaultUrlTransform, type Components } from 'react-markdown';
2
2
  import remarkGfm from 'remark-gfm';
3
- import { drawNodeId, mediaFileId } from '@mantle/content-core/markdown-refs';
3
+ import { drawNodeId, mediaFileId, presentNodeId } from '@mantle/content-core/markdown-refs';
4
4
  import { isEmbedded, type PresenterChrome } from './lib/presenter-chrome';
5
5
 
6
6
  /** Is `href` one of the app's reference schemes a note resolves itself
7
- * (`media:` a file, `draw:` a drawing)? */
7
+ * (`media:` a file, `draw:` a drawing, `present:` a canvas's snapshot)? */
8
8
  function isNoteRef(href: string): boolean {
9
9
  const s = href.trim();
10
- return mediaFileId(s) !== null || drawNodeId(s) !== null;
10
+ return mediaFileId(s) !== null || drawNodeId(s) !== null || presentNodeId(s) !== null;
11
11
  }
12
12
 
13
13
  /**
@@ -19,7 +19,8 @@ function isNoteRef(href: string): boolean {
19
19
  *
20
20
  * A note's own pictures and file links are written in the app's reference
21
21
  * schemes: `![alt](media:<file-id>)`, `[spec.pdf](media:<file-id>)`,
22
- * `![alt](draw:<draw-id>)`. `assetUrl` / `drawUrl` name the surface's byte
22
+ * `![alt](draw:<draw-id>)`, `![Title](present:<id>)`. `assetUrl` / `drawUrl` /
23
+ * `presentUrl` name the surface's byte
23
24
  * route for each (the public share passes its token routes, as it does for
24
25
  * the page presenter); the route decides what it serves. Without one, a
25
26
  * picture draws its alt text and a link its text, so nothing is asked for.
@@ -30,6 +31,7 @@ export function NotePresenter({
30
31
  chrome,
31
32
  assetUrl,
32
33
  drawUrl,
34
+ presentUrl,
33
35
  }: {
34
36
  view: { title: string; content: string };
35
37
  chrome?: PresenterChrome;
@@ -37,6 +39,9 @@ export function NotePresenter({
37
39
  assetUrl?: (fileId: string) => string;
38
40
  /** A `draw:` drawing's snapshot on this surface. */
39
41
  drawUrl?: (drawId: string) => string;
42
+ /** A `present:` canvas's snapshot on this surface, or null for one it
43
+ * does not show. */
44
+ presentUrl?: (presentId: string) => string | null;
40
45
  }) {
41
46
  const embedded = isEmbedded(chrome);
42
47
  /** The URL a reference resolves to, or null when this surface has no
@@ -47,6 +52,8 @@ export function NotePresenter({
47
52
  if (file) return assetUrl ? assetUrl(file) : null;
48
53
  const draw = drawNodeId(s);
49
54
  if (draw) return drawUrl ? drawUrl(draw) : null;
55
+ const canvas = presentNodeId(s);
56
+ if (canvas) return presentUrl ? presentUrl(canvas) : null;
50
57
  return null;
51
58
  };
52
59
  const components: Components = {
@@ -56,6 +63,10 @@ export function NotePresenter({
56
63
  return url ? (
57
64
  // eslint-disable-next-line @next/next/no-img-element -- token-routed share bytes; next/image cannot optimise them
58
65
  <img src={url} alt={alt ?? ''} />
66
+ ) : presentNodeId(src.trim()) ? (
67
+ // A canvas this surface does not show: a bare placeholder, never
68
+ // the alt (it may carry a title the reader may not see).
69
+ <span className="text-muted-foreground">[canvas]</span>
59
70
  ) : (
60
71
  <span className="text-muted-foreground">[{alt?.trim() || 'image'}]</span>
61
72
  );
@@ -1,58 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { decodeNeatSpec, encodeNeatSpec, neatConfigFromSpec } from './neat-background';
3
-
4
- const SPEC = { v: 1 as const, seed: 2325271021, tone: 'auto' as const, speed: 2 };
5
-
6
- describe('decodeNeatSpec', () => {
7
- it('round-trips the canonical encoding', () => {
8
- expect(decodeNeatSpec(encodeNeatSpec(SPEC))).toEqual(SPEC);
9
- });
10
-
11
- it('rejects garbage as null, never a throw', () => {
12
- for (const bad of [null, '', '{}', '{"v":2}', 'not json', '{"v":1,"seed":-1}']) {
13
- expect(decodeNeatSpec(bad)).toBeNull();
14
- }
15
- });
16
- });
17
-
18
- describe('neatConfigFromSpec — the wash', () => {
19
- const long = {
20
- background: '#ffffff',
21
- primary: '#b85c23',
22
- accent: '#eeeeee',
23
- secondary: '#527575',
24
- };
25
- // What getComputedStyle actually returns on a deployed build: the compiled
26
- // stylesheet minifies hex custom properties to shorthand where possible.
27
- const short = { background: '#fff', primary: '#b85c23', accent: '#eee', secondary: '#527575' };
28
-
29
- it('produces the IDENTICAL config for shorthand #rgb and #rrggbb tokens', () => {
30
- // Whole-config equality on purpose: it pins the wash (a failed shorthand
31
- // parse degraded stops to the raw brand colour) AND the raw pass-throughs
32
- // (colors[0]/[4] and backgroundColor once carried '#fff' verbatim, which
33
- // Neat's parseInt-based parser reads as 0x000fff — electric blue).
34
- expect(neatConfigFromSpec(SPEC, short, 'light')).toEqual(
35
- neatConfigFromSpec(SPEC, long, 'light'),
36
- );
37
- });
38
-
39
- it('hands the shader only canonical six-digit hex, never shorthand', () => {
40
- const c = neatConfigFromSpec(SPEC, short, 'light');
41
- for (const stop of c.colors) expect(stop.color).toMatch(/^#[0-9a-f]{6}$/);
42
- expect(c.backgroundColor).toBe('#ffffff');
43
- });
44
-
45
- it('actually washes the brand colour toward the ground', () => {
46
- const washed = neatConfigFromSpec(SPEC, short, 'light').colors[1]?.color ?? '';
47
- // Raw primary (or its 1.08 shade, #c66c39-ish) means the mix silently
48
- // failed; a washed stop is much lighter than the brand colour.
49
- expect(washed).not.toBe('#b85c23');
50
- const mean =
51
- [1, 3, 5].map((i) => parseInt(washed.slice(i, i + 2), 16)).reduce((s, n) => s + n, 0) / 3;
52
- expect(mean).toBeGreaterThan(150);
53
- });
54
-
55
- it('is deterministic — same seed, same config', () => {
56
- expect(neatConfigFromSpec(SPEC, long, 'dark')).toEqual(neatConfigFromSpec(SPEC, long, 'dark'));
57
- });
58
- });
@@ -1,249 +0,0 @@
1
- import type { NeatConfig } from '@firecms/neat';
2
-
3
- /**
4
- * The Neat background — an animated WebGL gradient behind a whole surface,
5
- * generated in Settings → Appearance and stored on the brain's preferences
6
- * row. This module is the spec contract and the parameter derivation; it lives
7
- * HERE (published as @crossworks/share-ui) because two renderers consume it —
8
- * the jackdaw owner app (login screen, content area) and this repo's
9
- * server-rendered /s share surface — and the two must never disagree about
10
- * what a saved spec looks like.
11
- *
12
- * We store a SPEC, never colours: `{ v, seed, tone, speed }`. Every colour is
13
- * derived from the LIVE theme tokens at paint time, so one saved background
14
- * follows all ~40 colour themes and light/dark mode by construction — a
15
- * stored hex would break silently on most themes, exactly like a hardcoded
16
- * class would. The seed drives a deterministic PRNG for every other Neat
17
- * parameter, so "the background I saved" is reproducible from four numbers,
18
- * and "Generate" is just a re-roll of the seed.
19
- *
20
- * The derived colours are washes: each brand colour is pulled most of the way
21
- * into `--background` before it reaches the shader. That is the legibility
22
- * guarantee — the gradient reads as a tint of the page surface, never a
23
- * poster fighting the text sitting on it.
24
- */
25
-
26
- export type NeatTone = 'auto' | 'darker' | 'lighter';
27
-
28
- export type NeatBackgroundSpec = {
29
- v: 1;
30
- /** Seeds the PRNG that derives every Neat parameter. */
31
- seed: number;
32
- /** Push the wash below the page surface ('darker'), above it ('lighter'),
33
- * or follow the mode — dark mode darkens, light mode lightens ('auto'). */
34
- tone: NeatTone;
35
- /** Animation speed, 0 (still) to {@link NEAT_SPEED_MAX}. */
36
- speed: number;
37
- };
38
-
39
- export const NEAT_SPEED_MAX = 6;
40
- export const NEAT_DEFAULT_SPEED = 2;
41
-
42
- /** Storage cap, mirrored by the server route — the canonical encoding of a
43
- * valid spec is ~60 chars, so this is a garbage guard, not a limit. */
44
- export const NEAT_BACKGROUND_MAX = 200;
45
-
46
- const TONES: readonly NeatTone[] = ['auto', 'darker', 'lighter'];
47
-
48
- /** Canonical wire encoding — fixed key order so equal specs compare equal as
49
- * strings (the UI's dirty check and the renderer's effect key rely on it). */
50
- export function encodeNeatSpec(spec: NeatBackgroundSpec): string {
51
- return JSON.stringify({ v: 1, seed: spec.seed, tone: spec.tone, speed: spec.speed });
52
- }
53
-
54
- /** Parse + shape-check a stored value. Garbage ⇒ null, never a throw — the
55
- * same lenient contract every appearance preference follows on read. */
56
- export function decodeNeatSpec(raw: unknown): NeatBackgroundSpec | null {
57
- if (typeof raw !== 'string' || raw.length === 0 || raw.length > NEAT_BACKGROUND_MAX) return null;
58
- let parsed: unknown;
59
- try {
60
- parsed = JSON.parse(raw);
61
- } catch {
62
- return null;
63
- }
64
- if (!parsed || typeof parsed !== 'object') return null;
65
- const o = parsed as Record<string, unknown>;
66
- if (o.v !== 1) return null;
67
- if (typeof o.seed !== 'number' || !Number.isInteger(o.seed) || o.seed < 0 || o.seed > 0xffffffff)
68
- return null;
69
- if (typeof o.tone !== 'string' || !(TONES as readonly string[]).includes(o.tone)) return null;
70
- if (typeof o.speed !== 'number' || !Number.isFinite(o.speed) || o.speed < 0) return null;
71
- return {
72
- v: 1,
73
- seed: o.seed,
74
- tone: o.tone as NeatTone,
75
- speed: Math.min(o.speed, NEAT_SPEED_MAX),
76
- };
77
- }
78
-
79
- export function randomNeatSpec(
80
- prev?: Pick<NeatBackgroundSpec, 'tone' | 'speed'>,
81
- ): NeatBackgroundSpec {
82
- return {
83
- v: 1,
84
- seed: Math.floor(Math.random() * 0xffffffff),
85
- tone: prev?.tone ?? 'auto',
86
- speed: prev?.speed ?? NEAT_DEFAULT_SPEED,
87
- };
88
- }
89
-
90
- /** The tokens the shader needs, resolved to literal hex — WebGL cannot read
91
- * `var()`, same constraint as the DiceBear ramp in theme-ramp.ts. */
92
- export type NeatThemeTokens = {
93
- background: string;
94
- primary: string;
95
- accent: string;
96
- secondary: string;
97
- };
98
-
99
- /** Deterministic PRNG (mulberry32) — same seed, same background, forever. */
100
- function mulberry32(seed: number): () => number {
101
- let a = seed >>> 0;
102
- return () => {
103
- a |= 0;
104
- a = (a + 0x6d2b79f5) | 0;
105
- let t = Math.imul(a ^ (a >>> 15), 1 | a);
106
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
107
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
108
- };
109
- }
110
-
111
- function hexToRgb(hex: string): [number, number, number] | null {
112
- const t = hex.trim();
113
- // Shorthand #rgb MUST parse: the compiled stylesheets minify hex custom
114
- // properties (#ffffff → #fff, #eeeeee → #eee), so this is what
115
- // getComputedStyle actually returns on deployed builds. Rejecting it made
116
- // mixHex silently return the RAW brand colour — no wash, a saturated
117
- // poster instead of a tint — on exactly the themes whose tokens shorten,
118
- // and only in production (dev CSS is unminified). Light modes were hit
119
- // hardest because near-white grounds (#ffffff/#eeeeee) all shorten.
120
- const short = /^#?([0-9a-f]{3})$/i.exec(t)?.[1];
121
- if (short) {
122
- const c = (i: number) => parseInt(short.charAt(i) + short.charAt(i), 16);
123
- return [c(0), c(1), c(2)];
124
- }
125
- const digits = /^#?([0-9a-f]{6})$/i.exec(t)?.[1];
126
- if (!digits) return null;
127
- const n = parseInt(digits, 16);
128
- return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff];
129
- }
130
-
131
- function rgbToHex([r, g, b]: [number, number, number]): string {
132
- const c = (v: number) =>
133
- Math.max(0, Math.min(255, Math.round(v)))
134
- .toString(16)
135
- .padStart(2, '0');
136
- return `#${c(r)}${c(g)}${c(b)}`;
137
- }
138
-
139
- /** `amount` of `into` mixed over `from` — 0 keeps `from`, 1 lands on `into`. */
140
- function mixHex(from: string, into: string, amount: number): string {
141
- const a = hexToRgb(from);
142
- const b = hexToRgb(into);
143
- if (!a || !b) return from;
144
- return rgbToHex([
145
- a[0] + (b[0] - a[0]) * amount,
146
- a[1] + (b[1] - a[1]) * amount,
147
- a[2] + (b[2] - a[2]) * amount,
148
- ]);
149
- }
150
-
151
- /** Nudge toward black (factor < 1) or white (factor > 1). */
152
- function shadeHex(hex: string, factor: number): string {
153
- const rgb = hexToRgb(hex);
154
- if (!rgb) return hex;
155
- if (factor <= 1) return rgbToHex([rgb[0] * factor, rgb[1] * factor, rgb[2] * factor]);
156
- const up = factor - 1;
157
- return rgbToHex([
158
- rgb[0] + (255 - rgb[0]) * up,
159
- rgb[1] + (255 - rgb[1]) * up,
160
- rgb[2] + (255 - rgb[2]) * up,
161
- ]);
162
- }
163
-
164
- /** Canonical #rrggbb for any hex this module can parse; unparseable values
165
- * pass through untouched. EVERY colour handed to the shader goes through
166
- * this: Neat's own parser is `parseInt(hex, 16)` on whatever it gets, so a
167
- * shorthand `#fff` reads as the 24-bit int 0x000fff — rgb(0, 15, 255), an
168
- * electric blue poster where the page ground should be. That is precisely
169
- * what deployed light themes produced, because minified stylesheets shorten
170
- * near-white tokens to #fff/#eee. */
171
- function normalizeHex(hex: string): string {
172
- const rgb = hexToRgb(hex);
173
- return rgb ? rgbToHex(rgb) : hex;
174
- }
175
-
176
- const round1 = (n: number) => Math.round(n * 10) / 10;
177
- const round2 = (n: number) => Math.round(n * 100) / 100;
178
-
179
- /**
180
- * Spec + live tokens + mode → the full Neat config (minus `ref`/`resolution`,
181
- * which are the renderer's business). Pure and deterministic, so the settings
182
- * preview and the real surface can never disagree about what a saved spec
183
- * looks like.
184
- */
185
- export function neatConfigFromSpec(
186
- spec: NeatBackgroundSpec,
187
- tokens: NeatThemeTokens,
188
- mode: 'light' | 'dark',
189
- ): NeatConfig {
190
- const rnd = mulberry32(spec.seed);
191
- const range = (lo: number, hi: number) => lo + rnd() * (hi - lo);
192
- const darker = spec.tone === 'darker' || (spec.tone === 'auto' && mode === 'dark');
193
-
194
- // Tokens arrive as whatever getComputedStyle returns — on deployed builds
195
- // that includes minifier shorthand. Normalized ONCE here, so both our wash
196
- // math and the raw pass-throughs below hand the shader canonical hex.
197
- const background = normalizeHex(tokens.background);
198
- const primary = normalizeHex(tokens.primary);
199
- const accent = normalizeHex(tokens.accent);
200
- const secondary = normalizeHex(tokens.secondary);
201
-
202
- // A wash: pull the brand colour part-way into the page background, then
203
- // nudge the result off the surface in the chosen direction. Enough colour
204
- // to read as a real gradient, close enough to the surface that content
205
- // sitting on it never fights it.
206
- const wash = (hex: string, towardBg: number) =>
207
- shadeHex(mixHex(hex, background, towardBg), darker ? 0.88 : 1.08);
208
-
209
- return {
210
- colors: [
211
- { color: background, enabled: true, influence: round2(range(0.3, 0.6)) },
212
- {
213
- color: wash(primary, round2(range(0.25, 0.5))),
214
- enabled: true,
215
- influence: round2(range(0.5, 0.9)),
216
- },
217
- {
218
- color: wash(accent, round2(range(0.25, 0.55))),
219
- enabled: true,
220
- influence: round2(range(0.45, 0.85)),
221
- },
222
- {
223
- color: wash(secondary, round2(range(0.35, 0.6))),
224
- enabled: true,
225
- influence: round2(range(0.35, 0.75)),
226
- },
227
- { color: background, enabled: true, influence: round2(range(0.25, 0.55)) },
228
- ],
229
- speed: spec.speed,
230
- horizontalPressure: round1(range(2, 5)),
231
- verticalPressure: round1(range(2, 5)),
232
- waveFrequencyX: round1(range(2, 6)),
233
- waveFrequencyY: round1(range(2, 6)),
234
- waveAmplitude: round1(range(3, 7)),
235
- // Keep the shader's own light play gentle: strong shadows/highlights are
236
- // exactly what would carve text-hostile contrast into the surface.
237
- shadows: round1(range(0, darker ? 3 : 1.5)),
238
- highlights: round1(range(0, darker ? 1.5 : 3)),
239
- colorBrightness: darker ? 0.95 : 1,
240
- colorSaturation: round1(range(-1, 2.5)),
241
- colorBlending: round1(range(5, 9)),
242
- grainScale: 2,
243
- grainIntensity: round2(range(0.02, 0.1)),
244
- grainSpeed: 0.3,
245
- wireframe: false,
246
- backgroundColor: background,
247
- backgroundAlpha: 1,
248
- };
249
- }