kodeui 0.0.0-stage → 0.1.0

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.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -2
  3. package/bin/kodeui.mjs +89 -0
  4. package/package.json +37 -4
  5. package/skill/kodeui/SKILL.md +105 -0
  6. package/skill/kodeui/assets/tokens.css +40 -0
  7. package/skill/kodeui/components/aurora-input/AuroraInput.tsx +153 -0
  8. package/skill/kodeui/components/aurora-input/aurora-input.css +218 -0
  9. package/skill/kodeui/components/aurora-input/index.ts +2 -0
  10. package/skill/kodeui/components/bloom-wall/BloomWall.tsx +90 -0
  11. package/skill/kodeui/components/bloom-wall/bloom-wall.css +10 -0
  12. package/skill/kodeui/components/bloom-wall/engine.ts +1022 -0
  13. package/skill/kodeui/components/bloom-wall/icons/icons-a.ts +818 -0
  14. package/skill/kodeui/components/bloom-wall/icons/icons-b.ts +827 -0
  15. package/skill/kodeui/components/bloom-wall/icons/index.ts +25 -0
  16. package/skill/kodeui/components/bloom-wall/icons/types.ts +8 -0
  17. package/skill/kodeui/components/bloom-wall/index.ts +12 -0
  18. package/skill/kodeui/components/bloom-wall/paint.ts +113 -0
  19. package/skill/kodeui/components/bloom-wall/palettes.ts +32 -0
  20. package/skill/kodeui/components/blur-in-text/BlurInText.tsx +53 -0
  21. package/skill/kodeui/components/blur-in-text/blur-in-text.css +14 -0
  22. package/skill/kodeui/components/blur-in-text/index.ts +2 -0
  23. package/skill/kodeui/components/glass-reveal/GlassReveal.tsx +108 -0
  24. package/skill/kodeui/components/glass-reveal/glass-reveal.css +126 -0
  25. package/skill/kodeui/components/glass-reveal/index.ts +2 -0
  26. package/skill/kodeui/components/glow-card/GlowCard.tsx +67 -0
  27. package/skill/kodeui/components/glow-card/glow-card.css +134 -0
  28. package/skill/kodeui/components/glow-card/index.ts +2 -0
  29. package/skill/kodeui/components/launch-chip/LaunchChip.tsx +180 -0
  30. package/skill/kodeui/components/launch-chip/icons.tsx +119 -0
  31. package/skill/kodeui/components/launch-chip/index.ts +3 -0
  32. package/skill/kodeui/components/launch-chip/launch-chip.css +345 -0
  33. package/skill/kodeui/components/ring-reveal/RingReveal.tsx +84 -0
  34. package/skill/kodeui/components/ring-reveal/index.ts +4 -0
  35. package/skill/kodeui/components/ring-reveal/ring-reveal.css +10 -0
  36. package/skill/kodeui/components/ring-reveal/ring.ts +298 -0
  37. package/skill/kodeui/components/rolling-text/RollingText.tsx +121 -0
  38. package/skill/kodeui/components/rolling-text/index.ts +4 -0
  39. package/skill/kodeui/components/rolling-text/roll.ts +94 -0
  40. package/skill/kodeui/components/rolling-text/rolling-text.css +43 -0
  41. package/skill/kodeui/components/use-live-transcript/index.ts +2 -0
  42. package/skill/kodeui/components/use-live-transcript/useLiveTranscript.ts +215 -0
  43. package/skill/kodeui/components/voice-input/VoiceInput.tsx +273 -0
  44. package/skill/kodeui/components/voice-input/icons.tsx +27 -0
  45. package/skill/kodeui/components/voice-input/index.ts +4 -0
  46. package/skill/kodeui/components/voice-input/useVoiceRecorder.ts +289 -0
  47. package/skill/kodeui/components/voice-input/voice-input.css +34 -0
  48. package/skill/kodeui/components/voice-note/VoiceNote.tsx +170 -0
  49. package/skill/kodeui/components/voice-note/index.ts +3 -0
  50. package/skill/kodeui/components/voice-note/noteFile.ts +25 -0
  51. package/skill/kodeui/components/voice-note/voice-note.css +45 -0
  52. package/skill/kodeui/references/aurora-input.md +44 -0
  53. package/skill/kodeui/references/bloom-wall.md +59 -0
  54. package/skill/kodeui/references/blur-in-text.md +17 -0
  55. package/skill/kodeui/references/frameworks.md +46 -0
  56. package/skill/kodeui/references/glass-reveal.md +40 -0
  57. package/skill/kodeui/references/glow-card.md +48 -0
  58. package/skill/kodeui/references/launch-chip.md +37 -0
  59. package/skill/kodeui/references/recipes.md +77 -0
  60. package/skill/kodeui/references/ring-reveal.md +35 -0
  61. package/skill/kodeui/references/rolling-text.md +19 -0
  62. package/skill/kodeui/references/theming.md +45 -0
  63. package/skill/kodeui/references/use-live-transcript.md +28 -0
  64. package/skill/kodeui/references/voice-input.md +60 -0
  65. package/skill/kodeui/references/voice-note.md +22 -0
  66. package/skill/kodeui/scripts/add.mjs +192 -0
  67. package/skill/kodeui/scripts/manifest.json +92 -0
@@ -0,0 +1,1022 @@
1
+ /*
2
+ * Bloom Wall engine. No React in here: give it a <canvas> and call setActive().
3
+ *
4
+ * What it draws, in order:
5
+ * 1. The canvas is cut into 58 px cells, packed into 4x4, 3x3, 2x2 and 1x1 tiles
6
+ * (big tiles stay away from the calm centre where a headline usually sits).
7
+ * 2. Each tile gets one of 16 nature icons and one palette, never the same as a neighbour.
8
+ * 3. setActive(true): a night backdrop opens in a soft ring from the origin (0.85 s),
9
+ * tiles pop in by distance, and every tile wakes and sleeps on its own slow wave.
10
+ * Every couple of seconds a tile near a corner swells and the grid flexes around it.
11
+ * 4. setActive(false): the ring folds back into the origin. About a quarter of the
12
+ * tiles stay behind, flicker and go out with a small four-point sparkle.
13
+ *
14
+ * One requestAnimationFrame loop, Canvas 2D only. The loop sleeps when idle or when
15
+ * the tab is hidden, honours prefers-reduced-motion, and lowers its own resolution
16
+ * (then drops the soft washes) if frames get slow.
17
+ *
18
+ * Everything that decides where things go and how they move is a pure function,
19
+ * exported so scripts/parity.ts can test it.
20
+ */
21
+ import { ICONS, ICON_FAMILY, ICON_KINDS, type IconDraw, type IconKind } from './icons';
22
+ import {
23
+ TAU, clamp, clamp01, createTinter, easeInOutCubic, easeInOutQuart, easeOutCubic, hashA, hashB, hexRGB,
24
+ smoothstep, smootherstep, type Tinter,
25
+ } from './paint';
26
+ import { NATURE_PALETTES, SLEEP_GREY, type Palette, type RGB } from './palettes';
27
+
28
+ export { NATURE_PALETTES, SLEEP_GREY };
29
+ export type { Palette };
30
+
31
+ // ------------------------------------------------------------------ numbers
32
+ export const CELL_PX = 58; // grid pitch in CSS px
33
+ export const SWELL_PX = 28; // px a swelling tile gains
34
+ export const SWELL_SECONDS = 2.05; // one swell, in and out
35
+ export const RING_SECONDS = 0.85; // the ring reaches the far corner
36
+ export const RING_SECONDS_AGAIN = 0.588; // the ring when you come back mid-fold
37
+ export const POP_SECONDS = 0.42; // one tile popping in
38
+ export const POP_SPREAD = 0.42; // extra pop delay at the far corner
39
+ export const FOLD_SECONDS = 2.45; // the ring folding back in
40
+ const SWELL_SPOTS: ReadonlyArray<readonly [number, number]> = [
41
+ [0.16, 0.82], [0.84, 0.18], [0.84, 0.82], [0.16, 0.18], [0.14, 0.52], [0.86, 0.52],
42
+ ];
43
+
44
+ // ------------------------------------------------------------ time curves
45
+ /** How bright an icon's own shimmer is right now, 0..1. */
46
+ export function shimmerAt(time: number, phase: number, reduced: boolean): number {
47
+ if (reduced) return 0.45 + 0.12 * Math.sin(phase);
48
+ const quick = 0.5 + 0.5 * Math.sin(time * 3.55 + phase);
49
+ return clamp01(0.68 * quick * quick + 0.32 * (0.5 + 0.5 * Math.sin(time * 1.15 - phase * 0.7)));
50
+ }
51
+
52
+ /** How awake a tile is, 0..1: two slow waves with a seeded speed. */
53
+ export function wakeAt(time: number, seed: number, reduced: boolean): number {
54
+ const d = hashA(seed);
55
+ const rate = 0.31 + 0.21 * d;
56
+ const t = reduced ? 0 : time;
57
+ const wave = Math.sin(t * rate + seed + hashA(seed + 17.31) * TAU) + 0.22 * Math.sin(t * (rate * 1.73 + 0.05) + d * TAU);
58
+ return smoothstep(-0.42, 0.52, wave / 1.22);
59
+ }
60
+
61
+ /** 1 inside an oval around where a headline sits, 0 outside. Keeps the middle quiet. */
62
+ export function calmAt(x: number, y: number): number {
63
+ const a = (x - 0.5) / 0.36;
64
+ const b = (y - 0.42) / 0.27;
65
+ const v = clamp01((Math.sqrt(a * a + b * b) - 0.55) / 0.7);
66
+ return 1 - v * v * (3 - 2 * v);
67
+ }
68
+
69
+ /** A swell: ease in over 70 % of a second, hold, ease out. */
70
+ export function swellEnvelope(t: number, dur: number = SWELL_SECONDS): number {
71
+ if (t <= 0 || t >= dur || dur <= 0) return 0;
72
+ const unit = dur / 2.05;
73
+ const rise = 0.7 * unit;
74
+ const hold = 1.15 * unit;
75
+ if (t < rise) return easeInOutQuart(t / rise);
76
+ if (t <= hold) return 1;
77
+ return 1 - easeInOutQuart((t - hold) / (dur - hold));
78
+ }
79
+
80
+ /** The opening ring: how uncovered a point at normalised distance d is after `elapsed` seconds. */
81
+ export function ringCover(d: number, elapsed: number, dur: number = RING_SECONDS): number {
82
+ if (elapsed <= 0 || dur <= 0) return 0;
83
+ if (elapsed >= dur) return 1;
84
+ return smootherstep((easeOutCubic(elapsed / dur) * 1.42 - clamp01(d)) / 0.42);
85
+ }
86
+
87
+ /** The closing ring: the far edge goes first, the area by the origin last. */
88
+ export function foldCover(d: number, elapsed: number): number {
89
+ if (elapsed <= 0) return 1;
90
+ if (elapsed >= FOLD_SECONDS) return 0;
91
+ const lead = (1 - d) * 0.16;
92
+ return 1 - smootherstep((clamp01(elapsed / FOLD_SECONDS) - lead) / Math.max(0.05, 0.9 - d * 0.32 - lead));
93
+ }
94
+
95
+ /** Reduced motion: a plain 0.45 s fade. */
96
+ export const quietFade = (from: number, t: number) => (from <= 0 ? 0 : Math.max(0, from * (1 - smootherstep(t / 0.45))));
97
+
98
+ /** Read a 33-step snapshot at distance d, with linear blending. */
99
+ export function readTable(table: ArrayLike<number>, d: number): number {
100
+ const x = clamp(d, 0, 1) * 32;
101
+ const i = Math.floor(x);
102
+ const f = x - i;
103
+ return table[i] * (1 - f) + table[Math.min(32, i + 1)] * f;
104
+ }
105
+
106
+ // ------------------------------------------------------------------ layout
107
+ export interface Block { col: number; row: number; span: number }
108
+ export interface Tile extends Block {
109
+ id: number;
110
+ /** index into ICON_KINDS */
111
+ kind: number;
112
+ /** index into the palettes */
113
+ palette: number;
114
+ /** icon animation phase, radians */
115
+ phase: number;
116
+ /** seed of the wake wave */
117
+ wakeSeed: number;
118
+ /** tiny extra pop-in delay, s */
119
+ delay: number;
120
+ /** how long a straggler survives the fold, s */
121
+ life: number;
122
+ /** tie-break when picking stragglers */
123
+ rank: number;
124
+ }
125
+ export interface GridLine { edge: number; start: number; end: number }
126
+ export interface Layout {
127
+ cols: number; rows: number; cell: number;
128
+ /** top-left of the grid in CSS px (centred, overflowing a little on both sides) */
129
+ ox: number; oy: number;
130
+ tiles: Tile[];
131
+ swellTiles: Block[];
132
+ vLines: GridLine[];
133
+ hLines: GridLine[];
134
+ dots: { col: number; row: number }[];
135
+ }
136
+
137
+ /** Packs a cols x rows grid into square tiles. Same size in = same wall out. */
138
+ export function packCells(cols: number, rows: number, w: number, h: number): Block[] {
139
+ const taken = new Uint8Array(cols * rows);
140
+ const blocks: Block[] = [];
141
+ const free = (c: number, r: number, sw: number, sh: number) => {
142
+ if (c < 0 || r < 0 || c + sw > cols || r + sh > rows) return false;
143
+ for (let y = r; y < r + sh; y++) for (let x = c; x < c + sw; x++) if (taken[y * cols + x] !== 0) return false;
144
+ return true;
145
+ };
146
+ const put = (c: number, r: number, s: number) => {
147
+ blocks.push({ col: c, row: r, span: s });
148
+ for (let y = 0; y < s; y++) for (let x = 0; x < s; x++) taken[(r + y) * cols + (c + x)] = s;
149
+ };
150
+ const large = w >= 1200 && h >= 750;
151
+ const medium = w >= 640 && h >= 420;
152
+
153
+ // 4x4: two on a large canvas, one on a medium one, never in the calm centre
154
+ const want4 = large ? 2 : medium && cols >= 10 && rows >= 8 ? 1 : 0;
155
+ const placed4: [number, number][] = [];
156
+ if (want4 > 0 && cols >= 6 && rows >= 5) {
157
+ const cMin = cols >= 10 ? 1 : 0, cMax = cols >= 10 ? cols - 5 : cols - 4;
158
+ const rMin = rows >= 8 ? 1 : 0, rMax = rows >= 8 ? rows - 5 : rows - 4;
159
+ const spots: { c: number; r: number; score: number }[] = [];
160
+ for (let c = cMin; c <= cMax; c++) {
161
+ for (let r = rMin; r <= rMax; r++) {
162
+ if (calmAt((c + 2) / cols, (r + 2) / rows) > 0.28) continue;
163
+ spots.push({ c, r, score: Math.abs((c + 2) / cols - 0.5) * 0.6 + hashB(c * 41 + r * 23 + cols * 5 + rows * 11 + 211) });
164
+ }
165
+ }
166
+ spots.sort((a, b) => b.score - a.score);
167
+ for (const s of spots) {
168
+ const apart = placed4.every(([pc, pr]) => Math.max(Math.abs(s.c - pc), Math.abs(s.r - pr)) >= 7);
169
+ if (apart && free(s.c, s.r, 4, 4)) {
170
+ put(s.c, s.r, 4);
171
+ placed4.push([s.c, s.r]);
172
+ if (placed4.length >= want4) break;
173
+ }
174
+ }
175
+ }
176
+
177
+ // 3x3, at least one cell clear of any other big tile
178
+ const want3 = large ? 6 : medium ? 3 : cols >= 7 && rows >= 7 ? 2 : 1;
179
+ {
180
+ const cMin = cols >= 10 ? 1 : 0, cMax = Math.max(cMin, cols >= 10 ? cols - 4 : cols - 3);
181
+ const rMin = rows >= 8 ? 1 : 0, rMax = Math.max(rMin, rows >= 8 ? rows - 4 : rows - 3);
182
+ const spots: { c: number; r: number; score: number }[] = [];
183
+ for (let c = cMin; c <= cMax; c++) {
184
+ for (let r = rMin; r <= rMax; r++) {
185
+ if (calmAt((c + 1.5) / cols, (r + 1.5) / rows) > 0.32) continue;
186
+ spots.push({ c, r, score: hashB(c * 31 + r * 17 + cols * 7 + rows * 13 + 101) });
187
+ }
188
+ }
189
+ spots.sort((a, b) => b.score - a.score);
190
+ const crowded = (c: number, r: number, s: number, pad: number) => {
191
+ const x0 = Math.max(0, c - pad), x1 = Math.min(cols - 1, c + s - 1 + pad);
192
+ const y0 = Math.max(0, r - pad), y1 = Math.min(rows - 1, r + s - 1 + pad);
193
+ for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) if (taken[y * cols + x] >= 3) return true;
194
+ return false;
195
+ };
196
+ let count = 0;
197
+ for (const s of spots) {
198
+ if (free(s.c, s.r, 3, 3) && !crowded(s.c, s.r, 3, 1)) {
199
+ put(s.c, s.r, 3);
200
+ if (++count >= want3) break;
201
+ }
202
+ }
203
+ }
204
+
205
+ // keep about 12 % of cells (in 3x3 groups) as singles, so 2x2s don't take everything
206
+ for (let r = 0; r < rows; r++) {
207
+ for (let c = 0; c < cols; c++) {
208
+ if (taken[r * cols + c] === 0 && hashB(Math.floor(c / 3) * 17 + Math.floor(r / 3) * 31 + cols * 3 + 7) < 0.12) taken[r * cols + c] = 1;
209
+ }
210
+ }
211
+
212
+ // 2x2 on a loose checkerboard, 17.5 % of the area
213
+ {
214
+ const spots: { c: number; r: number; tier: number; score: number }[] = [];
215
+ for (let r = 0; r <= rows - 2; r++) {
216
+ for (let c = 0; c <= cols - 2; c++) {
217
+ if (!free(c, r, 2, 2)) continue;
218
+ const tier = (c + Math.floor(r / 8)) % 2 === 0 && (r + Math.floor(c / 8)) % 2 === 0 ? 0 : 1;
219
+ spots.push({ c, r, tier, score: hashB(c * 29 + r * 43 + cols * 11 + 59) });
220
+ }
221
+ }
222
+ spots.sort((a, b) => a.tier - b.tier || b.score - a.score);
223
+ const quota = Math.round(cols * rows * 0.175);
224
+ let count = 0;
225
+ for (const s of spots) {
226
+ if (count >= quota) break;
227
+ if (free(s.c, s.r, 2, 2)) { put(s.c, s.r, 2); count++; }
228
+ }
229
+ }
230
+
231
+ // the rest are singles
232
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (taken[r * cols + c] <= 1) put(c, r, 1);
233
+ return blocks;
234
+ }
235
+
236
+ /** The tiles that swell: the small tile nearest each anchor, away from the edge and the calm centre. */
237
+ export function pickSwellTiles(cols: number, rows: number, tiles: readonly Block[], owner: ArrayLike<number>): Block[] {
238
+ const mx = cols >= 8 ? 2 : cols >= 5 ? 1 : 0;
239
+ const my = rows >= 8 ? 2 : rows >= 5 ? 1 : 0;
240
+ const picked: Block[] = [];
241
+ for (const [fx, fy] of SWELL_SPOTS) {
242
+ const tc = clamp(Math.round(fx * (cols - 1)), mx, cols - 1 - mx);
243
+ const tr = clamp(Math.round(fy * (rows - 1)), my, rows - 1 - my);
244
+ let best: Block | null = null;
245
+ let bestD = Infinity;
246
+ for (const t of tiles) {
247
+ if (t.span > 2) continue;
248
+ if (t.col < mx || t.row < my || t.col + t.span > cols - mx || t.row + t.span > rows - my) continue;
249
+ if (calmAt((t.col + t.span * 0.5) / cols, (t.row + t.span * 0.5) / rows) > 0.35) continue;
250
+ const d = Math.hypot(t.col + t.span * 0.5 - tc, t.row + t.span * 0.5 - tr);
251
+ if (d < bestD) { bestD = d; best = t; }
252
+ }
253
+ if (!best) {
254
+ const id = owner[tr * cols + tc];
255
+ if (id >= 0 && tiles[id].span <= 2) best = tiles[id];
256
+ }
257
+ const b = best;
258
+ if (b && !picked.some((p) => p.col === b.col && p.row === b.row)) picked.push({ col: b.col, row: b.row, span: b.span });
259
+ }
260
+ return picked;
261
+ }
262
+
263
+ /** The whole wall for a canvas of width x height CSS px. */
264
+ export function buildLayout(width: number, height: number, paletteCount = NATURE_PALETTES.length): Layout {
265
+ const w = Math.max(240, width), h = Math.max(200, height);
266
+ const cols = Math.max(4, Math.ceil(w / CELL_PX));
267
+ const rows = Math.max(4, Math.ceil(h / CELL_PX));
268
+ const ox = Math.floor((w - cols * CELL_PX) / 2);
269
+ const oy = Math.floor((h - rows * CELL_PX) / 2);
270
+ const blocks = packCells(cols, rows, w, h);
271
+ const owner: number[] = new Array(cols * rows).fill(-1);
272
+ const tiles: Tile[] = [];
273
+ const touching = (c: number, r: number, s: number) => {
274
+ const ids: number[] = [];
275
+ const add = (x: number, y: number) => {
276
+ if (x < 0 || y < 0 || x >= cols || y >= rows) return;
277
+ const id = owner[y * cols + x];
278
+ if (id >= 0 && !ids.includes(id)) ids.push(id);
279
+ };
280
+ for (let i = -1; i <= s; i++) { add(c + i, r - 1); add(c + i, r + s); }
281
+ for (let i = 0; i < s; i++) { add(c - 1, r + i); add(c + s, r + i); }
282
+ return ids;
283
+ };
284
+ const firstOpen = (count: number, start: number, step: number, used: (k: number) => boolean) => {
285
+ for (let i = 0; i < count; i++) {
286
+ const k = (start + i * step) % count;
287
+ if (!used(k)) return k;
288
+ }
289
+ return start;
290
+ };
291
+ const kinds = ICON_KINDS.length;
292
+ for (const b of blocks) {
293
+ const { col, row, span } = b;
294
+ const id = tiles.length;
295
+ const seed = col * 19 + row * 37 + cols * 7 + rows * 13 + span * 5;
296
+ const near = touching(col, row, span);
297
+ const kind = firstOpen(kinds, Math.floor(hashB(seed + 3) * kinds), 5, (k) => near.some((n) => tiles[n].kind === k));
298
+ const palette = firstOpen(paletteCount, Math.floor(hashB(seed + 9) * paletteCount), 1, (k) => near.some((n) => tiles[n].palette === k));
299
+ tiles.push({
300
+ id, col, row, span, kind, palette,
301
+ phase: hashB(seed + 67) * TAU,
302
+ wakeSeed: id * 1.618 + hashB(seed + 79) * 3.7,
303
+ delay: hashB(seed + 53) * 0.05,
304
+ life: 2.15 + hashB(seed + 97) * 1.15,
305
+ rank: hashB(seed + 41),
306
+ });
307
+ for (let y = 0; y < span; y++) for (let x = 0; x < span; x++) owner[(row + y) * cols + (col + x)] = id;
308
+ }
309
+
310
+ // hairlines only where two different tiles meet
311
+ const vLines: GridLine[] = [];
312
+ for (let c = 1; c < cols; c++) {
313
+ let from = -1;
314
+ for (let r = 0; r <= rows; r++) {
315
+ const split = r < rows && owner[r * cols + c - 1] !== owner[r * cols + c];
316
+ if (split && from < 0) from = r;
317
+ if (!split && from >= 0) { vLines.push({ edge: c, start: from, end: r }); from = -1; }
318
+ }
319
+ }
320
+ const hLines: GridLine[] = [];
321
+ for (let r = 1; r < rows; r++) {
322
+ let from = -1;
323
+ for (let c = 0; c <= cols; c++) {
324
+ const split = c < cols && owner[(r - 1) * cols + c] !== owner[r * cols + c];
325
+ if (split && from < 0) from = c;
326
+ if (!split && from >= 0) { hLines.push({ edge: r, start: from, end: c }); from = -1; }
327
+ }
328
+ }
329
+ // a 2 px dot where a horizontal line crosses or meets a vertical one
330
+ const dots: { col: number; row: number }[] = [];
331
+ for (let c = 1; c < cols; c++) {
332
+ for (let r = 1; r < rows; r++) {
333
+ const a = owner[(r - 1) * cols + c - 1], b = owner[(r - 1) * cols + c];
334
+ const e = owner[r * cols + c - 1], f = owner[r * cols + c];
335
+ if (a === b && a === e && a === f) continue;
336
+ const across = a !== e || b !== f;
337
+ if ((a === b && e === f) || !across) continue;
338
+ dots.push({ col: c, row: r });
339
+ }
340
+ }
341
+ return { cols, rows, cell: CELL_PX, ox, oy, tiles, swellTiles: pickSwellTiles(cols, rows, tiles, owner), vLines, hLines, dots };
342
+ }
343
+
344
+ // --------------------------------------------------------- the flexing grid
345
+ export interface Swell { col: number; row: number; span: number; start: number; dur: number; amount: number }
346
+
347
+ /** Which swells are running at `time` (s since the wall opened). */
348
+ export function swellsAt(layout: Layout, time: number): Swell[] {
349
+ const list = layout.swellTiles;
350
+ if (list.length === 0 || time < 0.35) return [];
351
+ const period = layout.cols >= 14 && layout.rows >= 12 ? 1.85 : 2.25;
352
+ const since = time - 0.35;
353
+ const last = Math.floor(since / period);
354
+ const out: Swell[] = [];
355
+ for (let i = Math.max(0, Math.floor((since - SWELL_SECONDS) / period) + 1); i <= last; i++) {
356
+ const start = 0.35 + i * period;
357
+ const age = time - start;
358
+ if (age <= 0 || age >= SWELL_SECONDS) continue;
359
+ const t = list[i % list.length];
360
+ if (out.some((o) => Math.abs(o.col - t.col) <= 5 && Math.abs(o.row - t.row) <= 5)) continue;
361
+ out.push({ col: t.col, row: t.row, span: t.span, start, dur: SWELL_SECONDS, amount: SWELL_PX });
362
+ }
363
+ return out;
364
+ }
365
+
366
+ /** Grow a band of rows or columns; the neighbours give the space back, so the total never changes. */
367
+ export function flexBands(deltas: number[], start: number, span: number, amount: number, env: number, envLag: number): void {
368
+ const n = deltas.length;
369
+ if (start < 0 || start + span > n || span <= 0 || amount <= 0 || env <= 0) return;
370
+ const near: number[] = [];
371
+ if (start - 1 >= 0) near.push(start - 1);
372
+ if (start + span < n) near.push(start + span);
373
+ if (near.length === 0) return;
374
+ const far: number[] = [];
375
+ if (start - 2 >= 0) far.push(start - 2);
376
+ if (start + span + 1 < n) far.push(start + span + 1);
377
+ const grow = (amount * env) / span;
378
+ const farGive = far.length > 0 ? -0.15 * amount * envLag : 0;
379
+ const nearGive = -(amount * env + farGive * far.length) / near.length;
380
+ for (let i = 0; i < span; i++) deltas[start + i] += grow;
381
+ for (const i of near) deltas[i] += nearGive;
382
+ for (const i of far) deltas[i] += farGive;
383
+ }
384
+
385
+ /** Pixel edges of n bands of `size` px starting at `start`, each nudged by its delta. */
386
+ export function bandEdges(n: number, start: number, size: number, deltas: ArrayLike<number>): number[] {
387
+ const edges: number[] = new Array(n + 1);
388
+ edges[0] = start;
389
+ let at = start;
390
+ for (let i = 0; i < n; i++) {
391
+ at += size + (deltas[i] || 0);
392
+ edges[i + 1] = Math.round(at);
393
+ }
394
+ return edges;
395
+ }
396
+
397
+ /**
398
+ * The tiles that stay behind during the fold: 26 % of each region of a 4 x 3 grid,
399
+ * small tiles first, then line icons, then the ones that are awake.
400
+ */
401
+ export function pickStragglers(layout: Layout, wakeById: ArrayLike<number>): Set<number> {
402
+ const regions: Tile[][] = Array.from({ length: 12 }, () => []);
403
+ for (const t of layout.tiles) {
404
+ const ry = clamp(Math.floor(((t.row + t.span * 0.5) / layout.rows) * 3), 0, 2);
405
+ const rx = clamp(Math.floor(((t.col + t.span * 0.5) / layout.cols) * 4), 0, 3);
406
+ regions[ry * 4 + rx].push(t);
407
+ }
408
+ const keep = new Set<number>();
409
+ for (const group of regions) {
410
+ if (group.length === 0) continue;
411
+ group.sort((a, b) => {
412
+ const sa = a.span <= 2 ? 0 : 1, sb = b.span <= 2 ? 0 : 1;
413
+ if (sa !== sb) return sa - sb;
414
+ const fa = ICON_FAMILY[ICON_KINDS[a.kind]], fb = ICON_FAMILY[ICON_KINDS[b.kind]];
415
+ if (fa !== fb) return fa - fb;
416
+ const wa = (wakeById[a.id] || 0) > 0.25 ? 0 : 1, wb = (wakeById[b.id] || 0) > 0.25 ? 0 : 1;
417
+ return wa - wb || a.rank - b.rank;
418
+ });
419
+ const n = Math.max(1, Math.round(group.length * 0.26));
420
+ for (let i = 0; i < n && i < group.length; i++) keep.add(group[i].id);
421
+ }
422
+ return keep;
423
+ }
424
+
425
+ // ------------------------------------------------------ per tile transitions
426
+ export interface TileMotion {
427
+ alpha: number;
428
+ scale: number;
429
+ /** s since the pop-in started */
430
+ inT: number;
431
+ inFromAlpha: number;
432
+ inFromScale: number;
433
+ /** s since the fold started */
434
+ outT: number;
435
+ outFromAlpha: number;
436
+ /** stays behind during the fold */
437
+ linger: boolean;
438
+ /** strength of the sparkle, 0..1 */
439
+ sparkle: number;
440
+ /** a lingering tile is kept at least this awake */
441
+ wakeFloor: number;
442
+ }
443
+ export const restingMotion = (v = 0): TileMotion => ({
444
+ alpha: v, scale: v > 0 ? 1 : 0.86,
445
+ inT: 0, inFromAlpha: v, inFromScale: v > 0 ? 1 : 0.86,
446
+ outT: 0, outFromAlpha: v,
447
+ linger: false, sparkle: 0, wakeFloor: 0,
448
+ });
449
+
450
+ /** Advance a pop-in by dt. */
451
+ export function popIn(m: TileMotion, dt: number, dur: number, delay: number): void {
452
+ m.inT += dt;
453
+ const t = m.inT - delay;
454
+ if (t <= 0) { m.alpha = m.inFromAlpha; m.scale = m.inFromScale; return; }
455
+ const e = easeOutCubic(t / Math.max(0.01, dur));
456
+ m.alpha = m.inFromAlpha + (1 - m.inFromAlpha) * e;
457
+ m.scale = m.inFromScale + (1 - m.inFromScale) * e;
458
+ }
459
+
460
+ /** Where a tile is in the fold, from m.outT. `time` drives the straggler flicker. */
461
+ export function foldOut(m: TileMotion, tile: Tile, d: number, time: number, reduced: boolean): void {
462
+ if (reduced) { m.alpha = quietFade(m.outFromAlpha, m.outT); m.scale = 1; m.sparkle = 0; m.wakeFloor = 0; return; }
463
+ if (m.linger) {
464
+ const t = m.outT, life = tile.life, from = m.outFromAlpha;
465
+ if (from <= 0 || t >= life) { m.alpha = 0; m.scale = 0.78; m.sparkle = 0; m.wakeFloor = 0; return; }
466
+ const hold = (1 - clamp01(d)) * 0.42; // tiles near the origin hold a little longer
467
+ if (t <= hold) { m.alpha = from; m.scale = 1; m.sparkle = 0; m.wakeFloor = 0.738; return; }
468
+ const p = clamp01((t - hold) / Math.max(0.25, life - hold));
469
+ const flicker = 0.68 + 0.32 * (0.5 + 0.5 * Math.sin(time * 7.5 + tile.phase * 3.7));
470
+ const a = clamp01(from * Math.pow(1 - Math.pow(p, 2.4), 1.2) * flicker);
471
+ m.alpha = a;
472
+ m.scale = 1 - 0.22 * easeInOutCubic(p);
473
+ m.sparkle = a * smootherstep((p - 0.06) / 0.24) * (1 - smootherstep((p - 0.78) / 0.22));
474
+ m.wakeFloor = 0.9 * (0.82 + 0.18 * smootherstep(p / 0.2));
475
+ return;
476
+ }
477
+ let k = m.outT;
478
+ if (k <= 0) k = 1;
479
+ else {
480
+ const wait = (1 - clamp01(d)) * 0.85;
481
+ k = k <= wait ? 1 : 1 - easeInOutCubic((k - wait) / 0.85);
482
+ }
483
+ m.alpha = m.outFromAlpha * k;
484
+ m.scale = 1 - 0.1 * (1 - k);
485
+ m.sparkle = 0;
486
+ m.wakeFloor = 0;
487
+ }
488
+
489
+ // ---------------------------------------------------------------- the look
490
+ export interface BloomTheme {
491
+ /** the night backdrop: a diagonal of three close colours */
492
+ backdrop: [string, string, string];
493
+ /** "r, g, b" of the faint light behind the centre */
494
+ glow: string;
495
+ /** "r, g, b" of the vignette */
496
+ vignette: string;
497
+ /** "r, g, b" of the hairlines and junction dots (a moss tone) */
498
+ ink: string;
499
+ }
500
+ export const NIGHT_THEME: BloomTheme = {
501
+ backdrop: ['#060c09', '#0c120f', '#070d0a'],
502
+ glow: '232, 241, 235',
503
+ vignette: '0, 0, 0',
504
+ ink: '168, 204, 180',
505
+ };
506
+
507
+ /** The four-point sparkle a straggler leaves as it goes out. */
508
+ function drawSparkle(ctx: CanvasRenderingContext2D, x: number, y: number, size: number, rgb: RGB, alpha: number, phase: number) {
509
+ alpha = clamp01(alpha);
510
+ if (alpha <= 0.02) return;
511
+ const sx = x + size * 0.24 * Math.cos(phase * 1.7);
512
+ const sy = y + size * 0.24 * Math.sin(phase * 1.7);
513
+ const R = clamp(size * 0.32, 10, 20);
514
+ const glowR = size * 0.58;
515
+ const [r, g, b] = rgb;
516
+ ctx.save();
517
+ let fill = ctx.createRadialGradient(x, y, 0, x, y, glowR);
518
+ fill.addColorStop(0, `rgba(${r}, ${g}, ${b}, ${(0.24 * alpha).toFixed(3)})`);
519
+ fill.addColorStop(0.55, `rgba(${r}, ${g}, ${b}, ${(0.08 * alpha).toFixed(3)})`);
520
+ fill.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
521
+ ctx.fillStyle = fill;
522
+ ctx.beginPath(); ctx.arc(x, y, glowR, 0, TAU); ctx.fill();
523
+ fill = ctx.createRadialGradient(sx, sy, 0, sx, sy, R);
524
+ fill.addColorStop(0, `rgba(255, 255, 255, ${(0.88 * alpha).toFixed(3)})`);
525
+ fill.addColorStop(0.32, `rgba(${r}, ${g}, ${b}, ${(0.62 * alpha).toFixed(3)})`);
526
+ fill.addColorStop(1, `rgba(${r}, ${g}, ${b}, 0)`);
527
+ ctx.fillStyle = fill;
528
+ ctx.beginPath(); ctx.arc(sx, sy, R, 0, TAU); ctx.fill();
529
+ const star = (len: number, waist: number) => {
530
+ const wd = Math.max(0.75, len * waist);
531
+ ctx.beginPath();
532
+ ctx.moveTo(sx, sy - len); ctx.lineTo(sx + wd, sy - wd); ctx.lineTo(sx + len, sy); ctx.lineTo(sx + wd, sy + wd);
533
+ ctx.lineTo(sx, sy + len); ctx.lineTo(sx - wd, sy + wd); ctx.lineTo(sx - len, sy); ctx.lineTo(sx - wd, sy - wd);
534
+ ctx.closePath(); ctx.fill();
535
+ };
536
+ ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${(0.92 * alpha).toFixed(3)})`; star(R, 0.11);
537
+ ctx.fillStyle = `rgba(255, 255, 255, ${(0.94 * alpha).toFixed(3)})`; star(R * 0.44, 0.16);
538
+ ctx.restore();
539
+ }
540
+
541
+ // ------------------------------------------------------------------ engine
542
+ export type BloomState = 'idle' | 'active' | 'fading';
543
+
544
+ export interface BloomEngineOptions {
545
+ /** Where the ring starts, in the canvas's CSS px. Read when the wall opens and on resize. Default: (50 %, 24 %). */
546
+ origin?: () => { x: number; y: number };
547
+ palettes?: readonly Palette[];
548
+ /** Replace the icon set (same 16 names). */
549
+ icons?: Record<IconKind, IconDraw>;
550
+ theme?: Partial<BloomTheme>;
551
+ /** Called when a fold has finished and the canvas is clear. */
552
+ onIdle?: () => void;
553
+ }
554
+
555
+ interface Rect { x0: number; y0: number; w: number; h: number; grow: number; tile: Tile }
556
+
557
+ export class BloomEngine {
558
+ readonly canvas: HTMLCanvasElement;
559
+ readonly ctx: CanvasRenderingContext2D | null;
560
+ state: BloomState = 'idle';
561
+ /** 1 = real time, 0.25 = slow motion */
562
+ timeScale = 1;
563
+ fastFade = false;
564
+ /** seconds the wall has been running (frozen under reduced motion) */
565
+ time = 0;
566
+ /** fold speed multiplier (eases to 4 for a fast fold) */
567
+ speed = 1;
568
+ w = 0; h = 0; dpr = 1;
569
+ grid: Layout | null = null;
570
+ /** the backdrop's own reveal state */
571
+ backdrop: TileMotion = restingMotion(0);
572
+ motion: TileMotion[] = [];
573
+ /** normalised distance of each tile from the origin */
574
+ dist: number[] = [];
575
+ /** how awake each tile was in the last frame */
576
+ wake: number[] = [];
577
+ ox = 512; oy = 180; reach = 900;
578
+ /** came back while folding */
579
+ again = false;
580
+ inSnap: Float32Array | null = null;
581
+ outSnap: Float32Array | null = null;
582
+ /** 0 = full, 1 = DPR 1, 2 = DPR 1 and no washes */
583
+ quality = 0;
584
+ frameAvg = 0;
585
+ frames = 0;
586
+
587
+ private opts: BloomEngineOptions;
588
+ private palettes: readonly Palette[] = NATURE_PALETTES;
589
+ private tinter: Tinter;
590
+ private paletteRGB: { primary: RGB; glow: RGB }[] = [];
591
+ private icons: Record<IconKind, IconDraw>;
592
+ private theme: BloomTheme;
593
+ private raf: number | null = null;
594
+ private lastTs: number | null = null;
595
+ private mq: MediaQueryList | null;
596
+ private ro: ResizeObserver | null = null;
597
+ private iconError = false;
598
+ private readonly onResize = () => { this.measure(); if (this.state !== 'idle') this.paint(); };
599
+ private readonly onVisibility = () => {
600
+ if (document.visibilityState === 'hidden') this.stop();
601
+ else if (this.state !== 'idle') this.start();
602
+ };
603
+
604
+ constructor(canvas: HTMLCanvasElement, opts: BloomEngineOptions = {}) {
605
+ this.canvas = canvas;
606
+ this.ctx = canvas.getContext('2d');
607
+ this.opts = opts;
608
+ this.icons = opts.icons ?? ICONS;
609
+ this.theme = { ...NIGHT_THEME, ...opts.theme };
610
+ this.tinter = createTinter(NATURE_PALETTES, SLEEP_GREY);
611
+ this.usePalettes(opts.palettes ?? NATURE_PALETTES);
612
+ // read on every frame, so an OS setting change applies at once
613
+ this.mq = typeof window !== 'undefined' && window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : null;
614
+ if (typeof window !== 'undefined') window.addEventListener('resize', this.onResize);
615
+ if (typeof ResizeObserver !== 'undefined') {
616
+ this.ro = new ResizeObserver(this.onResize);
617
+ this.ro.observe(canvas);
618
+ }
619
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', this.onVisibility);
620
+ }
621
+
622
+ get reduced(): boolean { return !!(this.mq && this.mq.matches); }
623
+
624
+ // ---------------------------------------------------------------- public
625
+ /** true: open from the origin and breathe. false: fold back in. */
626
+ setActive(on: boolean): void {
627
+ if (on) {
628
+ this.measure();
629
+ if (this.state === 'idle') {
630
+ this.time = 0; this.again = false; this.inSnap = this.outSnap = null; this.speed = 1;
631
+ this.backdrop = restingMotion(0);
632
+ for (let i = 0; i < this.motion.length; i++) this.motion[i] = restingMotion(0);
633
+ this.state = 'active';
634
+ } else if (this.state === 'fading') {
635
+ // back mid-fold: carry on from what is on screen, faster
636
+ this.again = true; this.speed = 1;
637
+ this.inSnap = this.coverTable(); this.outSnap = null;
638
+ this.backdrop.inFromAlpha = this.backdrop.alpha; this.backdrop.inT = 0;
639
+ for (const m of this.motion) {
640
+ m.inFromAlpha = m.alpha; m.inFromScale = m.scale; m.inT = 0;
641
+ m.linger = false; m.sparkle = 0; m.wakeFloor = 0;
642
+ }
643
+ this.state = 'active';
644
+ }
645
+ this.start();
646
+ } else if (this.state === 'active') {
647
+ this.outSnap = this.coverTable(); this.inSnap = null;
648
+ this.backdrop.outFromAlpha = this.backdrop.alpha; this.backdrop.outT = 0;
649
+ const grid = this.grid;
650
+ if (grid) {
651
+ for (let i = 0; i < grid.tiles.length; i++) if (!this.wake[i]) this.wake[i] = wakeAt(this.time, grid.tiles[i].wakeSeed, this.reduced);
652
+ }
653
+ const keep = grid ? pickStragglers(grid, this.wake) : new Set<number>();
654
+ this.motion.forEach((m, i) => {
655
+ m.outFromAlpha = m.alpha; m.outT = 0; m.linger = keep.has(i); m.sparkle = 0; m.wakeFloor = 0;
656
+ });
657
+ this.state = 'fading';
658
+ this.start();
659
+ }
660
+ }
661
+
662
+ /** The quick fold used after a click. */
663
+ setFastFade(on: boolean): void { this.fastFade = !!on; }
664
+
665
+ setOrigin(origin: (() => { x: number; y: number }) | undefined): void { this.opts.origin = origin; }
666
+
667
+ setPalettes(palettes: readonly Palette[]): void {
668
+ if (palettes === this.palettes || palettes.length === 0) return;
669
+ const regrid = palettes.length !== this.palettes.length;
670
+ this.usePalettes(palettes);
671
+ if (regrid && this.grid) this.measure(true);
672
+ if (this.state !== 'idle') this.paint();
673
+ }
674
+
675
+ setIcons(icons: Record<IconKind, IconDraw>): void { this.icons = icons; }
676
+
677
+ destroy(): void {
678
+ this.stop();
679
+ this.state = 'idle';
680
+ if (typeof window !== 'undefined') window.removeEventListener('resize', this.onResize);
681
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', this.onVisibility);
682
+ if (this.ro) this.ro.disconnect();
683
+ this.ro = null;
684
+ if (this.ctx) {
685
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0);
686
+ this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
687
+ }
688
+ }
689
+
690
+ private usePalettes(palettes: readonly Palette[]) {
691
+ this.palettes = palettes;
692
+ this.tinter = createTinter(palettes, SLEEP_GREY);
693
+ this.paletteRGB = palettes.map((p) => ({ primary: hexRGB(p.primary), glow: hexRGB(p.glow) }));
694
+ }
695
+
696
+ // ---------------------------------------------------------------- layout
697
+ /** Size the canvas to its box and rebuild the wall if the size changed. */
698
+ measure(force = false): void {
699
+ const rect = this.canvas.getBoundingClientRect();
700
+ const win = typeof window !== 'undefined' ? window : null;
701
+ let w = rect.width || (win && win.innerWidth) || 1024;
702
+ let h = rect.height || (win && win.innerHeight) || 768;
703
+ const dpr = this.quality >= 1 ? 1 : clamp((win && win.devicePixelRatio) || 1, 1, 2);
704
+ w = Math.max(1, Math.round(w)); h = Math.max(1, Math.round(h));
705
+ const changed = w !== this.w || h !== this.h;
706
+ this.w = w; this.h = h; this.dpr = dpr;
707
+ const pw = Math.round(w * dpr), ph = Math.round(h * dpr);
708
+ if (this.canvas.width !== pw) this.canvas.width = pw;
709
+ if (this.canvas.height !== ph) this.canvas.height = ph;
710
+ if (!changed && this.grid && !force) { this.aim(); return; }
711
+
712
+ // keep the average progress, so a resize mid-animation carries on instead of restarting.
713
+ // (Every tile gets the same average, so for that one fold the ring shape evens out.)
714
+ const n = this.motion.length;
715
+ let outT = 0, outFrom = 0, inFrom = 0, inFromScale = 0.86;
716
+ if (n > 0) {
717
+ outT = inFrom = outFrom = 0; inFromScale = 0;
718
+ for (const m of this.motion) { outT += m.outT; outFrom += m.outFromAlpha; inFrom += m.inFromAlpha; inFromScale += m.inFromScale; }
719
+ outT /= n; outFrom /= n; inFrom /= n; inFromScale /= n;
720
+ }
721
+ this.grid = buildLayout(w, h, this.palettes.length);
722
+ const grid = this.grid;
723
+ this.wake = new Array(grid.tiles.length).fill(0);
724
+ this.aim();
725
+ const reduced = this.reduced;
726
+ if (this.state === 'idle' || n === 0) {
727
+ this.motion = grid.tiles.map(() => restingMotion(0));
728
+ } else if (this.state === 'active') {
729
+ const dur = reduced ? 0.25 : POP_SECONDS;
730
+ this.motion = grid.tiles.map((t, i) => {
731
+ const m = restingMotion(inFrom);
732
+ m.inFromScale = inFromScale;
733
+ popIn(m, this.backdrop.inT, dur, reduced ? 0 : this.again ? this.dist[i] * 0.12 : this.dist[i] * POP_SPREAD + t.delay);
734
+ return m;
735
+ });
736
+ } else {
737
+ for (let i = 0; i < grid.tiles.length; i++) this.wake[i] = wakeAt(this.time, grid.tiles[i].wakeSeed, reduced);
738
+ const keep = pickStragglers(grid, this.wake);
739
+ this.motion = grid.tiles.map((t, i) => {
740
+ const m = restingMotion(outFrom);
741
+ m.outT = outT;
742
+ m.linger = keep.has(i);
743
+ foldOut(m, t, this.dist[i], this.time, reduced);
744
+ return m;
745
+ });
746
+ }
747
+ }
748
+
749
+ /** Read the origin and each tile's distance from it. */
750
+ private aim(): void {
751
+ const o = this.opts.origin ? this.opts.origin() : null;
752
+ this.ox = o ? clamp(o.x, 0, this.w) : this.w * 0.5;
753
+ this.oy = o ? clamp(o.y, 0, this.h) : this.h * 0.24;
754
+ const { w, h, ox, oy } = this;
755
+ this.reach = Math.max(1, Math.hypot(ox, oy), Math.hypot(w - ox, oy), Math.hypot(ox, h - oy), Math.hypot(w - ox, h - oy));
756
+ const grid = this.grid;
757
+ if (!grid) return;
758
+ if (this.dist.length !== grid.tiles.length) this.dist = new Array(grid.tiles.length).fill(0);
759
+ grid.tiles.forEach((t, i) => {
760
+ this.dist[i] = clamp01(Math.hypot(grid.ox + (t.col + t.span * 0.5) * grid.cell - ox, grid.oy + (t.row + t.span * 0.5) * grid.cell - oy) / this.reach);
761
+ });
762
+ }
763
+
764
+ // --------------------------------------------------------------- the ring
765
+ /** How uncovered the wall is at normalised distance d (0 at the origin, 1 at the far corner). */
766
+ cover(d: number): number {
767
+ d = clamp01(d);
768
+ if (this.state === 'idle') return 0;
769
+ if (this.reduced) return clamp01(this.backdrop.alpha);
770
+ if (this.state === 'active') {
771
+ const r = ringCover(d, this.backdrop.inT, this.again ? RING_SECONDS_AGAIN : RING_SECONDS);
772
+ return this.inSnap ? clamp01(Math.max(readTable(this.inSnap, d), r)) : r;
773
+ }
774
+ return (this.outSnap ? readTable(this.outSnap, d) : 1) * foldCover(d, this.backdrop.outT);
775
+ }
776
+
777
+ coverTable(): Float32Array {
778
+ const t = new Float32Array(33);
779
+ for (let i = 0; i <= 32; i++) t[i] = this.cover(i / 32);
780
+ return t;
781
+ }
782
+
783
+ /** A radial gradient from the origin whose alpha follows cover(d). Used as a mask. */
784
+ private coverGradient(ctx: CanvasRenderingContext2D, rgb: string, alpha: number): CanvasGradient {
785
+ const g = ctx.createRadialGradient(this.ox, this.oy, 0, this.ox, this.oy, this.reach);
786
+ for (let i = 0; i <= 10; i++) g.addColorStop(i / 10, `rgba(${rgb}, ${(alpha * this.cover(i / 10)).toFixed(3)})`);
787
+ return g;
788
+ }
789
+
790
+ // ------------------------------------------------------------------ loop
791
+ start(): void {
792
+ if (this.raf !== null || this.state === 'idle' || typeof document === 'undefined' || document.visibilityState === 'hidden') return;
793
+ this.lastTs = null;
794
+ const tick = (ts: number) => {
795
+ this.raf = null;
796
+ if (this.state === 'idle') return;
797
+ const dt = Math.min(0.1, this.lastTs === null ? 1 / 60 : Math.max(0, (ts - this.lastTs) / 1000));
798
+ this.lastTs = ts;
799
+ if (this.step(dt) && (this.state as BloomState) !== 'idle' && document.visibilityState !== 'hidden') this.raf = requestAnimationFrame(tick);
800
+ };
801
+ this.raf = requestAnimationFrame(tick);
802
+ }
803
+
804
+ stop(): void {
805
+ if (this.raf !== null) cancelAnimationFrame(this.raf);
806
+ this.raf = null;
807
+ this.lastTs = null;
808
+ }
809
+
810
+ /** Advance by dt seconds of real time and paint. Returns false when the loop may sleep. */
811
+ step(dt: number): boolean {
812
+ dt *= this.timeScale;
813
+ const reduced = this.reduced;
814
+ if (!reduced) this.time += dt;
815
+ if (!this.grid) this.measure();
816
+ const grid = this.grid;
817
+ if (!grid) return false;
818
+ if (this.state === 'idle') return false;
819
+ const bg = this.backdrop;
820
+ if (this.state === 'active') {
821
+ const bgDur = reduced ? 0.25 : this.again ? 0.42 : RING_SECONDS;
822
+ bg.inT += dt;
823
+ bg.alpha = reduced ? bg.inFromAlpha + (1 - bg.inFromAlpha) * easeOutCubic(bg.inT / bgDur) : this.cover(0);
824
+ let done = this.cover(1) >= 1;
825
+ const dur = reduced ? 0.25 : POP_SECONDS;
826
+ for (let i = 0; i < this.motion.length; i++) {
827
+ const delay = reduced ? 0 : this.again ? this.dist[i] * 0.12 : this.dist[i] * POP_SPREAD + grid.tiles[i].delay;
828
+ popIn(this.motion[i], dt, dur, delay);
829
+ if (this.motion[i].alpha < 1) done = false;
830
+ }
831
+ this.paint();
832
+ return !reduced || !done; // keeps running while open: the tiles breathe
833
+ }
834
+ // fading
835
+ const target = this.fastFade ? (reduced ? 2.25 : 4) : 1;
836
+ this.speed += (target - this.speed) * Math.min(1, dt * 14);
837
+ dt *= this.speed;
838
+ bg.outT += dt;
839
+ bg.alpha = reduced ? quietFade(bg.outFromAlpha, bg.outT) : this.cover(0);
840
+ let brightest = bg.alpha;
841
+ let lingering = false;
842
+ for (let i = 0; i < this.motion.length; i++) {
843
+ const m = this.motion[i], tile = grid.tiles[i];
844
+ m.outT += dt;
845
+ foldOut(m, tile, this.dist[i], this.time, reduced);
846
+ if (!reduced && m.linger && m.outT < tile.life) lingering = true;
847
+ if (m.alpha > brightest) brightest = m.alpha;
848
+ }
849
+ if (!lingering && brightest <= 0.002) { this.finish(); return false; }
850
+ this.paint();
851
+ return true;
852
+ }
853
+
854
+ private finish(): void {
855
+ this.again = false; this.outSnap = this.inSnap = null;
856
+ this.backdrop.alpha = 0;
857
+ for (const m of this.motion) { m.alpha = 0; m.scale = 1; m.linger = false; m.sparkle = 0; m.wakeFloor = 0; }
858
+ if (this.ctx) {
859
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0);
860
+ this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
861
+ }
862
+ this.stop();
863
+ this.state = 'idle';
864
+ if (this.opts.onIdle) this.opts.onIdle();
865
+ }
866
+
867
+ // ------------------------------------------------------------ one frame
868
+ paint(): void {
869
+ const ctx = this.ctx, grid = this.grid;
870
+ if (!ctx || !grid || this.w <= 0 || this.h <= 0) return;
871
+ const startedAt = performance.now();
872
+ const { w, h, dpr, time } = this;
873
+ const reduced = this.reduced;
874
+ const theme = this.theme;
875
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
876
+ ctx.clearRect(0, 0, w, h);
877
+ const r0 = this.cover(0), r1 = this.cover(1);
878
+
879
+ // 1. night backdrop: a dark diagonal, a faint light behind the centre, a vignette, cut by the ring
880
+ if (r0 > 0.002 || r1 > 0.002) {
881
+ ctx.save();
882
+ const open = reduced || (r0 >= 0.999 && r1 >= 0.999);
883
+ if (reduced) ctx.globalAlpha = clamp01(r0);
884
+ const diag = ctx.createLinearGradient(0, 0, w, h);
885
+ diag.addColorStop(0, theme.backdrop[0]);
886
+ diag.addColorStop(0.5, theme.backdrop[1]);
887
+ diag.addColorStop(1, theme.backdrop[2]);
888
+ ctx.fillStyle = diag; ctx.fillRect(0, 0, w, h);
889
+ const light = ctx.createRadialGradient(w * 0.5, h * 0.44, 0, w * 0.5, h * 0.44, Math.max(w, h) * 0.58);
890
+ light.addColorStop(0, `rgba(${theme.glow}, 0.025)`);
891
+ light.addColorStop(0.6, `rgba(${theme.glow}, 0.008)`);
892
+ light.addColorStop(1, `rgba(${theme.vignette}, 0)`);
893
+ ctx.fillStyle = light; ctx.fillRect(0, 0, w, h);
894
+ const vig = ctx.createRadialGradient(w * 0.5, h * 0.46, Math.min(w, h) * 0.24, w * 0.5, h * 0.5, Math.max(w, h) * 0.74);
895
+ vig.addColorStop(0, `rgba(${theme.vignette}, 0)`);
896
+ vig.addColorStop(1, `rgba(${theme.vignette}, 0.36)`);
897
+ ctx.fillStyle = vig; ctx.fillRect(0, 0, w, h);
898
+ if (!open) {
899
+ ctx.globalCompositeOperation = 'destination-in';
900
+ ctx.fillStyle = this.coverGradient(ctx, '0, 0, 0', 1);
901
+ ctx.fillRect(0, 0, w, h);
902
+ }
903
+ ctx.restore();
904
+ }
905
+
906
+ // 2. the flexing grid: swelling tiles push their row and column apart
907
+ const colD: number[] = new Array(grid.cols).fill(0), rowD: number[] = new Array(grid.rows).fill(0);
908
+ if (!reduced) {
909
+ for (const s of swellsAt(grid, time)) {
910
+ const age = time - s.start;
911
+ const env = swellEnvelope(age, s.dur);
912
+ const lag = Math.min(env, swellEnvelope(age - 0.07, s.dur));
913
+ flexBands(colD, s.col, s.span, s.amount, env, lag);
914
+ flexBands(rowD, s.row, s.span, s.amount, env, lag);
915
+ }
916
+ }
917
+ const xs = bandEdges(grid.cols, grid.ox, grid.cell, colD);
918
+ const ys = bandEdges(grid.rows, grid.oy, grid.cell, rowD);
919
+ const rects: Rect[] = grid.tiles.map((t) => {
920
+ const x0 = xs[t.col], x1 = xs[t.col + t.span], y0 = ys[t.row], y1 = ys[t.row + t.span];
921
+ const rw = Math.max(0, x1 - x0), rh = Math.max(0, y1 - y0), base = t.span * grid.cell;
922
+ return { x0, y0, w: rw, h: rh, grow: (rw * rh) / (base * base), tile: t };
923
+ });
924
+
925
+ // 3. tiles: a soft colour wash, the icon, the sparkle
926
+ const nPal = this.palettes.length;
927
+ const bgIn = this.backdrop.inT;
928
+ for (const R of rects) {
929
+ const tile = R.tile, m = this.motion[tile.id];
930
+ const op = m ? m.alpha : 0, sc = m ? m.scale : 1;
931
+ const sparkle = m ? m.sparkle : 0, floor = m ? m.wakeFloor : 0;
932
+ const wave = wakeAt(time, tile.wakeSeed, reduced);
933
+ // every tile flashes awake as the wall opens, then settles into its own rhythm
934
+ const flash = !reduced && this.state === 'active' && bgIn < 0.85
935
+ ? 0.68 * (1 - smootherstep(bgIn / 0.85)) * (1 - this.dist[tile.id] * 0.5) : 0;
936
+ const a = Math.max(wave, floor, flash);
937
+ this.wake[tile.id] = a;
938
+ if (a * op < 0.02 || R.w < 8 || R.h < 8) continue;
939
+ const sh = shimmerAt(time, tile.phase, reduced);
940
+ const swell = clamp01((R.grow - 0.72) / 0.65);
941
+ const k = reduced ? 0.48 : clamp(sh * 0.62 + swell * 0.45, 0.15, 1);
942
+ const cx = R.x0 + R.w * 0.5, cy = R.y0 + R.h * 0.5;
943
+ const pi = ((Math.trunc(tile.palette) % nPal) + nPal) % nPal;
944
+ const rgb = this.paletteRGB[pi];
945
+ const calm = calmAt(cx / w, cy / h) * (this.state === 'fading' && m && m.linger ? 0.1 : 1);
946
+ const iconAlpha = op * (1 - 0.45 * calm);
947
+ if (this.quality < 2) {
948
+ const wr = Math.max(R.w, R.h) * 0.54;
949
+ const wa = (0.032 + 0.078 * k) * op * a * (1 - 0.6 * calm);
950
+ const [gr, gg, gb] = rgb.glow;
951
+ const wash = ctx.createRadialGradient(cx, cy, 0, cx, cy, wr);
952
+ wash.addColorStop(0, `rgba(${gr}, ${gg}, ${gb}, ${wa.toFixed(3)})`);
953
+ wash.addColorStop(0.55, `rgba(${gr}, ${gg}, ${gb}, ${(wa * 0.35).toFixed(3)})`);
954
+ wash.addColorStop(1, `rgba(${gr}, ${gg}, ${gb}, 0)`);
955
+ ctx.fillStyle = wash; ctx.fillRect(R.x0, R.y0, R.w, R.h);
956
+ }
957
+ const size = Math.max(10, Math.min(R.w, R.h) * (tile.span === 1 ? 0.64 : tile.span === 2 ? 0.61 : 0.58) * sc);
958
+ this.paintIcon(ctx, tile, pi, cx, cy, size, k, clamp01(iconAlpha), clamp01(a));
959
+ if (sparkle > 0.02) drawSparkle(ctx, cx, cy, size, rgb.primary, sparkle * (1 - 0.45 * calm), tile.phase);
960
+ }
961
+
962
+ // 4. hairlines, outlines round awake tiles, junction dots, all cut by the ring
963
+ if (r0 > 0.002 || r1 > 0.002) {
964
+ ctx.save();
965
+ ctx.lineWidth = 1;
966
+ const open = !reduced && r0 >= 0.999 && r1 >= 0.999;
967
+ const ink = theme.ink;
968
+ const lineA = 0.12, dotA = 0.18;
969
+ ctx.strokeStyle = reduced || open ? `rgba(${ink}, ${(lineA * (reduced ? r0 : 1)).toFixed(3)})` : this.coverGradient(ctx, ink, lineA);
970
+ ctx.beginPath();
971
+ for (const e of grid.vLines) { const x = xs[e.edge] + 0.5; ctx.moveTo(x, ys[e.start]); ctx.lineTo(x, ys[e.end]); }
972
+ for (const e of grid.hLines) { const y = ys[e.edge] + 0.5; ctx.moveTo(xs[e.start], y); ctx.lineTo(xs[e.end], y); }
973
+ ctx.stroke();
974
+ for (const R of rects) {
975
+ const m = this.motion[R.tile.id];
976
+ const vis = Math.min(reduced ? r0 : this.cover(this.dist[R.tile.id] || 0), m ? m.alpha : 0);
977
+ if (vis <= 0.002) continue;
978
+ const lit = clamp01(((this.wake[R.tile.id] || 0) - 0.55) / 0.45);
979
+ if (lit <= 0) continue;
980
+ const alpha = (0.12 + 0.14 * clamp01((R.grow - 1) / 0.3)) * lit * lit * vis;
981
+ if (alpha < 0.01) continue;
982
+ const [pr, pg, pb] = this.paletteRGB[R.tile.palette % nPal].primary;
983
+ ctx.strokeStyle = `rgba(${pr}, ${pg}, ${pb}, ${alpha.toFixed(3)})`;
984
+ ctx.strokeRect(R.x0 + 0.5, R.y0 + 0.5, R.w, R.h);
985
+ }
986
+ ctx.fillStyle = reduced || open ? `rgba(${ink}, ${(dotA * (reduced ? r0 : 1)).toFixed(3)})` : this.coverGradient(ctx, ink, dotA);
987
+ for (const d of grid.dots) ctx.fillRect(xs[d.col] - 0.5, ys[d.row] - 0.5, 2, 2);
988
+ ctx.restore();
989
+ }
990
+
991
+ // 5. self-tuning: slow frames (over 12 ms on average) drop to DPR 1, then drop the washes
992
+ const ms = performance.now() - startedAt;
993
+ if (this.quality < 2) {
994
+ this.frameAvg = this.frames === 0 ? ms : this.frameAvg * 0.88 + ms * 0.12;
995
+ this.frames++;
996
+ if (this.frames >= 24 && this.frameAvg > 12) {
997
+ this.quality++; this.frames = 0; this.frameAvg = 0;
998
+ if (this.quality === 1 && this.dpr > 1) { this.measure(); this.paint(); }
999
+ }
1000
+ }
1001
+ }
1002
+
1003
+ private paintIcon(ctx: CanvasRenderingContext2D, tile: Tile, pi: number, cx: number, cy: number, size: number, k: number, alpha: number, awake: number) {
1004
+ if (alpha <= 0.01 || awake <= 0.02 || size <= 1) return;
1005
+ const sat = smoothstep(0.25, 1, awake); // grey -> colour
1006
+ const a = alpha * smoothstep(0.02, 0.25, awake) * (0.4 + 0.6 * sat);
1007
+ if (a <= 0.004) return;
1008
+ const tint = this.tinter(pi, sat);
1009
+ const iconTime = this.reduced ? tile.phase * 0.4 : this.time + tile.phase;
1010
+ const draw = this.icons[ICON_KINDS[tile.kind]];
1011
+ ctx.save();
1012
+ try {
1013
+ ctx.globalAlpha *= a;
1014
+ ctx.translate(cx, cy);
1015
+ draw(ctx, size * 0.44, iconTime, clamp01(k), tint);
1016
+ } catch (err) {
1017
+ if (!this.iconError) { this.iconError = true; console.error('[bloom-wall] icon', ICON_KINDS[tile.kind], err); }
1018
+ } finally {
1019
+ ctx.restore();
1020
+ }
1021
+ }
1022
+ }