@once-ui-system/fx 3.0.0-beta.1 → 3.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/WeatherFx.js CHANGED
@@ -2,23 +2,376 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { Flex, useReducedMotion } from "@once-ui-system/core";
4
4
  import { useEffect, useRef } from "react";
5
+ import { canvasColor, clampCount, createStage, isDarkBackground, pick, rand, watchTheme, } from "./internal/canvasStage.js";
6
+ import { cannotHover } from "./internal/pointer.js";
7
+ import { prefersReducedMotionNow } from "./internal/reducedMotion.js";
5
8
  import { speedFactor } from "./internal/speed.js";
6
- const WeatherFx = ({ ref: forwardedRef, type = "rain", speed: speedProp, colors = ["brand-solid-medium"], intensity = 50, angle = 0, duration, trigger = "mount", active = false, reducedMotion = "auto", children, ...rest }) => {
9
+ import { useControllableState } from "./internal/useControllableState.js";
10
+ const DEFAULT_COLORS = ["brand-solid-medium"];
11
+ const DEFAULT_LEAF_COLORS = ["brand-solid-medium", "accent-solid-medium"];
12
+ /** Lightning never flashes more often than this many seconds (WCAG 2.3.1: under three flashes a second). */
13
+ const LIGHTNING_MIN_INTERVAL = 0.5;
14
+ function spriteCache() {
15
+ const cache = new Map();
16
+ return {
17
+ get(key, draw) {
18
+ if (cache.has(key))
19
+ return cache.get(key) ?? null;
20
+ const canvas = document.createElement("canvas");
21
+ canvas.width = 64;
22
+ canvas.height = 64;
23
+ const ctx = canvas.getContext("2d");
24
+ if (!ctx) {
25
+ cache.set(key, null);
26
+ return null;
27
+ }
28
+ draw(ctx, 64);
29
+ cache.set(key, canvas);
30
+ return canvas;
31
+ },
32
+ };
33
+ }
34
+ function fallScene(stage, type, count, colorCount, angle) {
35
+ let particles = [];
36
+ const rad = (Math.max(-60, Math.min(60, angle)) * Math.PI) / 180;
37
+ const dx = Math.sin(rad);
38
+ const dy = Math.cos(rad);
39
+ // Wider than the box on the upwind side, so slanted weather reaches every corner.
40
+ const reachX = () => Math.tan(Math.abs(rad)) * stage.height;
41
+ const speedFor = (z) => type === "rain" ? rand(650, 800) + z * 600 : type === "snow" ? 22 + z * 60 : 40 + z * 55;
42
+ const spawn = (y) => {
43
+ const z = Math.random() ** 1.4; // more far than near
44
+ const reach = reachX();
45
+ return {
46
+ x: rand(-(dx > 0 ? reach : 0) - 20, stage.width + (dx < 0 ? reach : 0) + 20),
47
+ y,
48
+ z,
49
+ speed: speedFor(z),
50
+ phase: rand(0, Math.PI * 2),
51
+ vphase: type === "snow" ? rand(0.5, 1.3) : rand(0.4, 1),
52
+ sway: type === "snow" ? 8 + z * 22 : 20 + z * 40,
53
+ rot: rand(0, Math.PI * 2),
54
+ vrot: rand(-1.6, 1.6),
55
+ flip: rand(0, Math.PI * 2),
56
+ vflip: rand(-3, 3),
57
+ color: pick(colorCount),
58
+ };
59
+ };
60
+ const top = () => -40;
61
+ const start = (scatter) => {
62
+ const { height } = stage;
63
+ const missing = count - particles.length;
64
+ for (let i = 0; i < missing; i++) {
65
+ particles.push(spawn(scatter ? rand(-40, height) : rand(-height, 0) - 20));
66
+ }
67
+ };
68
+ const step = (dt, emitting) => {
69
+ const { width, height } = stage;
70
+ const reach = reachX() + 80;
71
+ let n = 0;
72
+ for (const p of particles) {
73
+ p.x += p.speed * dx * dt;
74
+ p.y += p.speed * dy * dt;
75
+ p.phase += p.vphase * dt;
76
+ p.rot += p.vrot * dt;
77
+ p.flip += p.vflip * dt;
78
+ const gone = p.y > height + 40 || p.x < -reach || p.x > width + reach;
79
+ if (!gone) {
80
+ particles[n++] = p;
81
+ }
82
+ else if (emitting) {
83
+ const fresh = spawn(top());
84
+ particles[n++] = fresh;
85
+ }
86
+ }
87
+ particles.length = n;
88
+ };
89
+ const draw = (colors, sprites) => {
90
+ const { ctx, dpr } = stage;
91
+ const color = (i) => colors[i] ?? colors[0];
92
+ if (type === "rain") {
93
+ ctx.lineCap = "round";
94
+ for (const p of particles) {
95
+ const length = 10 + p.z * 22;
96
+ const alpha = 0.28 + p.z * 0.55;
97
+ ctx.strokeStyle = color(p.color);
98
+ ctx.lineWidth = 0.6 + p.z * 1.1;
99
+ // A head and a fainter tail read as motion without a gradient per drop.
100
+ ctx.globalAlpha = alpha * 0.35;
101
+ ctx.beginPath();
102
+ ctx.moveTo(p.x - dx * length, p.y - dy * length);
103
+ ctx.lineTo(p.x - dx * length * 0.45, p.y - dy * length * 0.45);
104
+ ctx.stroke();
105
+ ctx.globalAlpha = alpha;
106
+ ctx.beginPath();
107
+ ctx.moveTo(p.x - dx * length * 0.45, p.y - dy * length * 0.45);
108
+ ctx.lineTo(p.x, p.y);
109
+ ctx.stroke();
110
+ }
111
+ return;
112
+ }
113
+ if (type === "snow") {
114
+ for (const p of particles) {
115
+ const c = color(p.color);
116
+ const sprite = sprites.get(`flake:${c}`, (s, size) => {
117
+ const r = size / 2;
118
+ const g = s.createRadialGradient(r, r, 0, r, r, r);
119
+ g.addColorStop(0, c);
120
+ g.addColorStop(0.45, c);
121
+ g.addColorStop(1, "transparent");
122
+ s.fillStyle = g;
123
+ s.fillRect(0, 0, size, size);
124
+ });
125
+ // Near flakes are larger and softer, far ones small and faint.
126
+ const radius = 1.8 + p.z * 5.2;
127
+ const x = p.x + Math.sin(p.phase) * p.sway;
128
+ ctx.globalAlpha = 0.35 + p.z * 0.6;
129
+ if (sprite) {
130
+ ctx.drawImage(sprite, x - radius, p.y - radius, radius * 2, radius * 2);
131
+ }
132
+ else {
133
+ ctx.fillStyle = c;
134
+ ctx.beginPath();
135
+ ctx.arc(x, p.y, radius * 0.6, 0, Math.PI * 2);
136
+ ctx.fill();
137
+ }
138
+ }
139
+ return;
140
+ }
141
+ // Leaves
142
+ for (const p of particles) {
143
+ const c1 = color(p.color);
144
+ const c2 = color(Math.min(p.color + 1, colors.length - 1));
145
+ const sprite = sprites.get(`leaf:${c1}:${c2}`, (s, size) => {
146
+ const w = size * 0.32;
147
+ const h = size * 0.48;
148
+ s.translate(size / 2, size / 2);
149
+ const g = s.createLinearGradient(-w, -h, w, h);
150
+ g.addColorStop(0, c1);
151
+ g.addColorStop(1, c2);
152
+ s.fillStyle = g;
153
+ s.beginPath();
154
+ s.moveTo(0, -h);
155
+ s.bezierCurveTo(w * 1.3, -h * 0.45, w * 0.9, h * 0.55, 0, h);
156
+ s.bezierCurveTo(-w * 0.9, h * 0.55, -w * 1.3, -h * 0.45, 0, -h);
157
+ s.fill();
158
+ // Midrib and stem.
159
+ s.strokeStyle = "rgba(0, 0, 0, 0.22)";
160
+ s.lineWidth = 1.5;
161
+ s.beginPath();
162
+ s.moveTo(0, -h * 0.85);
163
+ s.lineTo(0, h * 1.15);
164
+ s.stroke();
165
+ });
166
+ const size = 14 + p.z * 16;
167
+ const flip = Math.cos(p.flip);
168
+ const sx = flip >= 0 ? Math.max(0.15, flip) : Math.min(-0.15, flip);
169
+ const cos = Math.cos(p.rot);
170
+ const sin = Math.sin(p.rot);
171
+ const x = p.x + Math.sin(p.phase) * p.sway;
172
+ ctx.setTransform(dpr * cos * sx, dpr * sin * sx, -dpr * sin, dpr * cos, dpr * x, dpr * p.y);
173
+ ctx.globalAlpha = (0.6 + p.z * 0.35) * (0.6 + 0.4 * Math.abs(flip));
174
+ if (sprite) {
175
+ ctx.drawImage(sprite, -size / 2, -size / 2, size, size);
176
+ }
177
+ else {
178
+ ctx.fillStyle = c1;
179
+ ctx.fillRect(-size / 4, -size / 2, size / 2, size);
180
+ }
181
+ }
182
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
183
+ };
184
+ return {
185
+ start,
186
+ step,
187
+ draw,
188
+ alive: () => particles.length > 0,
189
+ clear: () => {
190
+ particles = [];
191
+ },
192
+ };
193
+ }
194
+ function lightningScene(stage, intensity, colorCount) {
195
+ let bolts = [];
196
+ let wait = 0;
197
+ let lastCount = 1;
198
+ const interval = () => Math.max(LIGHTNING_MIN_INTERVAL, (15 / Math.max(1, intensity)) * rand(0.75, 1.3));
199
+ const branch = (x, y, base, level, heading, thickness) => {
200
+ const segments = [];
201
+ const children = [];
202
+ const length = 3 + pick(4);
203
+ let a = heading;
204
+ for (let i = 0; i < length; i++) {
205
+ const step = base * 0.7 ** level * rand(0.6, 1.2);
206
+ a += rand(-0.4, 0.4);
207
+ x += Math.cos(a) * step;
208
+ y += Math.sin(a) * step;
209
+ segments.push({ x, y });
210
+ if (level < 3 && i > 0 && Math.random() < 0.35 - level * 0.1) {
211
+ const child = branch(x, y, base, level + 1, a + rand(-Math.PI / 2, Math.PI / 2), thickness);
212
+ children.push({ startIndex: i, ...child, thickness: thickness * 0.6 ** (level + 1) });
213
+ }
214
+ }
215
+ return { segments, children };
216
+ };
217
+ const bolt = (startX) => {
218
+ const segments = [{ x: startX, y: 0 }];
219
+ const branches = [];
220
+ const base = rand(12, 27);
221
+ const thickness = rand(2.2, 3.4);
222
+ let x = startX;
223
+ let y = 0;
224
+ let a = Math.PI / 2;
225
+ while (y < stage.height) {
226
+ const step = base * rand(0.5, 1.3);
227
+ a = Math.min((3 * Math.PI) / 4, Math.max(Math.PI / 4, a + rand(-0.3, 0.3)));
228
+ x += Math.cos(a) * step;
229
+ y += Math.sin(a) * step;
230
+ segments.push({ x, y });
231
+ if (segments.length > 2 && Math.random() < 0.35) {
232
+ const child = branch(x, y, base, 1, a + rand(-Math.PI / 3, Math.PI / 3), thickness);
233
+ branches.push({ startIndex: segments.length - 1, ...child, thickness: thickness * 0.6 });
234
+ }
235
+ }
236
+ return {
237
+ segments,
238
+ branches,
239
+ color: pick(colorCount),
240
+ opacity: rand(0.8, 1),
241
+ thickness,
242
+ life: rand(0.4, 0.6),
243
+ age: 0,
244
+ reveal: rand(0.08, 0.12),
245
+ };
246
+ };
247
+ const strike = () => {
248
+ // One strike is one flash, however many bolts it holds; a multi-bolt
249
+ // strike is followed by a single one for variety.
250
+ let count = 1;
251
+ if (lastCount === 1) {
252
+ if (intensity > 60 && Math.random() < 0.6)
253
+ count = 2 + pick(3);
254
+ else if (intensity > 30 && Math.random() < 0.5)
255
+ count = 2 + pick(2);
256
+ else if (intensity > 15 && Math.random() < 0.3)
257
+ count = 2;
258
+ }
259
+ lastCount = count;
260
+ for (let i = 0; i < count; i++) {
261
+ const b = bolt(rand(0.08, 0.92) * stage.width);
262
+ b.age = -i * 0.025;
263
+ bolts.push(b);
264
+ }
265
+ };
266
+ const path = (ctx, points, from, n) => {
267
+ ctx.beginPath();
268
+ if (from)
269
+ ctx.moveTo(from.x, from.y);
270
+ for (let i = 0; i < n; i++) {
271
+ const p = points[i];
272
+ if (i === 0 && !from)
273
+ ctx.moveTo(p.x, p.y);
274
+ else
275
+ ctx.lineTo(p.x, p.y);
276
+ }
277
+ };
278
+ const draw = (colors) => {
279
+ const { ctx, width, height } = stage;
280
+ ctx.lineCap = "round";
281
+ ctx.lineJoin = "round";
282
+ ctx.globalCompositeOperation = stage.dark ? "lighter" : "source-over";
283
+ for (const b of bolts) {
284
+ if (b.age < 0)
285
+ continue;
286
+ const progress = Math.min(1, b.age / b.reveal);
287
+ const t = b.age / b.life;
288
+ let alpha = b.opacity;
289
+ if (b.age < b.reveal)
290
+ alpha *= progress;
291
+ else if (t > 0.3)
292
+ alpha *= 1 - (t - 0.3) / 0.7;
293
+ const shown = Math.ceil(b.segments.length * progress);
294
+ const color = colors[b.color] ?? colors[0];
295
+ // The sky lights up faintly with the strike (a dark sky only: on a
296
+ // light page a tint would read as the page dimming).
297
+ if (stage.dark) {
298
+ ctx.globalAlpha = alpha * 0.06;
299
+ ctx.fillStyle = color;
300
+ ctx.fillRect(0, 0, width, height);
301
+ }
302
+ const strokeAll = (widthScale, a, style) => {
303
+ ctx.strokeStyle = style;
304
+ ctx.globalAlpha = alpha * a;
305
+ ctx.lineWidth = b.thickness * widthScale;
306
+ path(ctx, b.segments, null, shown);
307
+ ctx.stroke();
308
+ const walk = (branches, parent, parentShown) => {
309
+ for (const br of branches) {
310
+ if (br.startIndex >= parentShown)
311
+ continue;
312
+ const n = Math.ceil(br.segments.length * Math.min(1, (parentShown - br.startIndex) / 3));
313
+ ctx.lineWidth = br.thickness * widthScale;
314
+ path(ctx, br.segments, parent[br.startIndex], n);
315
+ ctx.stroke();
316
+ walk(br.children, br.segments, n);
317
+ }
318
+ };
319
+ walk(b.branches, b.segments, shown);
320
+ };
321
+ // Glow, body, then a bright core: three strokes instead of a shadow blur.
322
+ if (stage.dark) {
323
+ strokeAll(5, 0.12, color);
324
+ strokeAll(1.6, 0.55, color);
325
+ strokeAll(0.5, 0.9, "rgba(255, 255, 255, 0.9)");
326
+ }
327
+ else {
328
+ strokeAll(3, 0.08, color);
329
+ strokeAll(1.1, 0.95, color);
330
+ }
331
+ }
332
+ ctx.globalCompositeOperation = "source-over";
333
+ };
334
+ return {
335
+ start: () => {
336
+ wait = Math.min(0.4, interval());
337
+ },
338
+ step: (dt, emitting) => {
339
+ if (emitting && dt > 0) {
340
+ wait -= dt;
341
+ if (wait <= 0) {
342
+ strike();
343
+ wait = interval();
344
+ }
345
+ }
346
+ bolts = bolts.filter((b) => {
347
+ b.age += dt;
348
+ return b.age <= b.life;
349
+ });
350
+ },
351
+ draw: (colors) => draw(colors),
352
+ alive: () => bolts.length > 0,
353
+ clear: () => {
354
+ bolts = [];
355
+ },
356
+ };
357
+ }
358
+ const WeatherFx = ({ ref: forwardedRef, type = "rain", speed: speedProp, colors: colorsProp, intensity = 50, angle = 0, duration, trigger = "mount", active: activeProp, defaultActive, onActiveChange, reducedMotion = "auto", children, onClick, onMouseEnter, onMouseLeave, ...rest }) => {
7
359
  const speed = speedFactor(speedProp);
360
+ const colors = colorsProp ?? (type === "leaves" ? DEFAULT_LEAF_COLORS : DEFAULT_COLORS);
361
+ const colorsKey = colors.join("|");
362
+ const count = clampCount(intensity, 400);
8
363
  const { shouldAnimate } = useReducedMotion(reducedMotion);
364
+ const [active, setActive] = useControllableState({
365
+ value: activeProp,
366
+ defaultValue: defaultActive ?? trigger === "mount",
367
+ onChange: onActiveChange,
368
+ });
9
369
  const containerRef = useRef(null);
10
370
  const canvasRef = useRef(null);
11
- const animationRef = useRef(undefined);
12
- const particlesRef = useRef([]);
13
- const timeRef = useRef(0);
14
- // Manual starts off: the manual-trigger effect below turns emission on for
15
- // `active`, and only does so (creating the particles) when it is off. Seeding
16
- // it with `active` meant `<WeatherFx trigger="manual" active />` drew nothing.
17
- const isEmittingRef = useRef(trigger === "mount");
18
- const emitStartTimeRef = useRef(Date.now());
19
- const isHoveredRef = useRef(false);
20
- const lastLightningTimeRef = useRef(0);
21
- const lastBoltCountRef = useRef(0);
371
+ const activeRef = useRef(active);
372
+ activeRef.current = active;
373
+ const startedRef = useRef(false);
374
+ const runRef = useRef(null);
22
375
  useEffect(() => {
23
376
  if (forwardedRef) {
24
377
  if ("current" in forwardedRef) {
@@ -29,832 +382,132 @@ const WeatherFx = ({ ref: forwardedRef, type = "rain", speed: speedProp, colors
29
382
  }
30
383
  }
31
384
  }, [forwardedRef]);
385
+ // One scene per look: a new type, palette, pace, amount or angle starts afresh.
386
+ // biome-ignore lint/correctness/useExhaustiveDependencies: colorsKey stands for colors
32
387
  useEffect(() => {
33
388
  const canvas = canvasRef.current;
34
389
  const container = containerRef.current;
35
390
  if (!canvas || !container)
36
391
  return;
37
- const ctx = canvas.getContext("2d");
38
- if (!ctx)
39
- return;
40
- // Set canvas size
41
- let canvasWidth = 0;
42
- let canvasHeight = 0;
43
- const updateSize = () => {
44
- const rect = container.getBoundingClientRect();
45
- canvasWidth = rect.width;
46
- canvasHeight = rect.height;
47
- canvas.width = rect.width * 2; // 2x for retina
48
- canvas.height = rect.height * 2;
49
- canvas.style.width = `${rect.width}px`;
50
- canvas.style.height = `${rect.height}px`;
51
- ctx.scale(2, 2); // Scale for retina
52
- };
53
- updateSize();
54
- window.addEventListener("resize", updateSize);
55
- // Parse colors - convert token names to CSS variables
56
- const parsedColors = colors.map((color) => {
57
- const computedColor = getComputedStyle(container).getPropertyValue(`--${color}`);
58
- return computedColor || color;
59
- });
60
- // Initialize particles based on type
61
- const initializeRain = () => {
62
- const particles = [];
63
- // Calculate spawn area based on angle
64
- const angleRad = (angle * Math.PI) / 180;
65
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
66
- // Create initial rain drops
67
- for (let i = 0; i < intensity; i++) {
68
- // Expand spawn width to account for angle
69
- const spawnWidth = canvasWidth + horizontalOffset * 2;
70
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
71
- particles.push({
72
- x: spawnX,
73
- y: Math.random() * canvasHeight - canvasHeight, // Start above canvas
74
- length: 10 + Math.random() * 20, // Varying lengths
75
- speed: (2 + Math.random() * 3) * speed, // Varying speeds
76
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
77
- opacity: 0.3 + Math.random() * 0.5,
78
- thickness: 1 + Math.random() * 1.5,
79
- });
80
- }
81
- return particles;
82
- };
83
- // Initialize snow particles
84
- const initializeSnow = () => {
85
- const particles = [];
86
- // Calculate spawn area based on angle
87
- const angleRad = (angle * Math.PI) / 180;
88
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
89
- for (let i = 0; i < intensity; i++) {
90
- const depth = Math.random(); // 0 = far, 1 = near
91
- const size = 2 + depth * 4; // 2-6px, bigger = closer
92
- // Expand spawn width to account for angle
93
- const spawnWidth = canvasWidth + horizontalOffset * 2;
94
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
95
- particles.push({
96
- x: spawnX,
97
- y: Math.random() * canvasHeight - canvasHeight,
98
- size,
99
- speed: (0.3 + depth * 0.7) * speed, // 0.3-1.0x speed, closer = faster
100
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
101
- opacity: 0.4 + depth * 0.5, // 0.4-0.9, closer = more opaque
102
- swayAmplitude: 20 + Math.random() * 30, // 20-50px horizontal sway
103
- swaySpeed: 0.5 + Math.random() * 1, // Varying sway speeds
104
- swayOffset: Math.random() * Math.PI * 2, // Random starting phase
105
- depth,
106
- });
107
- }
108
- return particles;
109
- };
110
- // Initialize leaves particles
111
- const initializeLeaves = () => {
112
- const particles = [];
113
- // Calculate spawn area based on angle
114
- const angleRad = (angle * Math.PI) / 180;
115
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
116
- for (let i = 0; i < intensity; i++) {
117
- const depth = Math.random(); // 0 = far, 1 = near
118
- const width = 8 + depth * 12; // 8-20px, bigger = closer
119
- const height = width * (0.6 + Math.random() * 0.4); // Leaf aspect ratio
120
- // Expand spawn width to account for angle
121
- const spawnWidth = canvasWidth + horizontalOffset * 2;
122
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
123
- // Pick two colors for gradient (either from same color or adjacent colors)
124
- const colorIndex = Math.floor(Math.random() * parsedColors.length);
125
- const color1 = parsedColors[colorIndex];
126
- const color2 = parsedColors[Math.min(colorIndex + 1, parsedColors.length - 1)];
127
- particles.push({
128
- x: spawnX,
129
- y: Math.random() * canvasHeight - canvasHeight,
130
- width,
131
- height,
132
- speed: (0.4 + depth * 0.8) * speed, // 0.4-1.2x speed
133
- color1,
134
- color2,
135
- opacity: 0.6 + depth * 0.3, // 0.6-0.9
136
- swayAmplitude: 30 + Math.random() * 50, // 30-80px stronger sway
137
- swaySpeed: 0.3 + Math.random() * 0.7, // Slower sway for leaves
138
- swayOffset: Math.random() * Math.PI * 2,
139
- rotation: Math.random() * Math.PI * 2, // Random starting rotation
140
- rotationSpeed: (Math.random() - 0.5) * 0.08, // -0.04 to 0.04 rad/frame
141
- rotation3D: Math.random() * Math.PI * 2, // Random 3D flip angle
142
- rotation3DSpeed: (Math.random() - 0.5) * 0.06, // 3D tumbling speed
143
- depth,
144
- });
145
- }
146
- return particles;
147
- };
148
- // Recursive function to generate chaotic, organic branches
149
- const generateBranch = (startX, startY, baseSegmentLength, branchLevel, maxLevel, angle, parentThickness) => {
150
- const segments = [];
151
- const children = [];
152
- // Longer branches that decrease more gradually with depth
153
- const lengthMultiplier = 0.7 ** branchLevel;
154
- const branchLength = 3 + Math.floor(Math.random() * 4); // 3-6 segments
155
- let currentX = startX;
156
- let currentY = startY;
157
- let currentAngle = angle;
158
- for (let i = 0; i < branchLength; i++) {
159
- // Larger segments for longer branches
160
- const segmentLength = baseSegmentLength * lengthMultiplier * (0.6 + Math.random() * 0.6);
161
- // Add angular variation for organic chaos
162
- currentAngle += (Math.random() - 0.5) * 0.8;
163
- // Move in the current angle direction
164
- currentX += Math.cos(currentAngle) * segmentLength;
165
- currentY += Math.sin(currentAngle) * segmentLength;
166
- segments.push({ x: currentX, y: currentY });
167
- // Moderate probability of branching
168
- if (branchLevel < maxLevel && i > 0) {
169
- // Only primary branches get multiple attempts
170
- const branchAttempts = branchLevel === 1 ? 1 : 1;
171
- for (let attempt = 0; attempt < branchAttempts; attempt++) {
172
- // Lower probability: 35% at level 1, 25% at level 2, etc.
173
- const branchProbability = 0.35 - branchLevel * 0.1;
174
- if (Math.random() < branchProbability) {
175
- // Random angle deviation from current direction (-90 to +90 degrees)
176
- const angleDeviation = (Math.random() - 0.5) * Math.PI;
177
- const childAngle = currentAngle + angleDeviation;
178
- const childBranch = generateBranch(currentX, currentY, baseSegmentLength, branchLevel + 1, maxLevel, childAngle, parentThickness);
179
- if (childBranch.segments.length > 0) {
180
- children.push({
181
- startIndex: i,
182
- segments: childBranch.segments,
183
- thickness: parentThickness * 0.6 ** (branchLevel + 1),
184
- children: childBranch.children,
185
- });
186
- }
187
- }
188
- }
392
+ const motion = reducedMotion === false
393
+ ? true
394
+ : reducedMotion === true
395
+ ? false
396
+ : shouldAnimate && !prefersReducedMotionNow();
397
+ let palette = colors.map((c) => canvasColor(container, c));
398
+ let sprites = spriteCache();
399
+ let scene;
400
+ let stillOn = false;
401
+ const handle = createStage(canvas, container, {
402
+ frame: (_stage, dt) => {
403
+ if (!scene)
404
+ return false;
405
+ if (!motion) {
406
+ if (stillOn)
407
+ scene.draw(palette, sprites);
408
+ return false;
189
409
  }
190
- }
191
- return { segments, children };
192
- };
193
- // Generate lightning bolt with chaotic branches
194
- const generateLightningBolt = (startX, startY, endY) => {
195
- const segments = [];
196
- const branches = [];
197
- let currentX = startX;
198
- let currentY = startY;
199
- const baseSegmentLength = 12 + Math.random() * 15; // Smaller segments for detail
200
- const mainThickness = 2.5 + Math.random() * 1.5;
201
- segments.push({ x: currentX, y: currentY });
202
- // Main bolt with more erratic path
203
- let currentAngle = Math.PI / 2; // Start going down (90 degrees)
204
- while (currentY < endY) {
205
- // Vary segment length significantly
206
- const segmentLength = baseSegmentLength * (0.5 + Math.random() * 0.8);
207
- // Add significant angular variation for jagged appearance
208
- currentAngle += (Math.random() - 0.5) * 0.6;
209
- // Ensure we're generally moving downward
210
- if (currentAngle < Math.PI / 4)
211
- currentAngle = Math.PI / 4; // Min 45 degrees
212
- if (currentAngle > (3 * Math.PI) / 4)
213
- currentAngle = (3 * Math.PI) / 4; // Max 135 degrees
214
- currentX += Math.cos(currentAngle) * segmentLength;
215
- currentY += Math.sin(currentAngle) * segmentLength;
216
- segments.push({ x: currentX, y: currentY });
217
- // Moderate chance of branching (35%) for balanced appearance
218
- if (Math.random() < 0.35 && segments.length > 2) {
219
- // Random angle deviation (-120 to +120 degrees from current)
220
- const angleDeviation = (Math.random() - 0.5) * ((2 * Math.PI) / 3);
221
- const branchAngle = currentAngle + angleDeviation;
222
- const primaryBranch = generateBranch(currentX, currentY, baseSegmentLength, 1, 3, // Max 3 levels to reduce chaos
223
- branchAngle, mainThickness);
224
- if (primaryBranch.segments.length > 0) {
225
- branches.push({
226
- startIndex: segments.length - 1,
227
- segments: primaryBranch.segments,
228
- thickness: mainThickness * 0.6,
229
- children: primaryBranch.children,
230
- });
231
- }
410
+ scene.step(dt * speed, activeRef.current);
411
+ scene.draw(palette, sprites);
412
+ return activeRef.current || scene.alive();
413
+ },
414
+ resize: () => {
415
+ if (!motion && stillOn && scene) {
416
+ scene.clear();
417
+ scene.start(true);
232
418
  }
233
- }
234
- return {
235
- x: startX,
236
- y: startY,
237
- segments,
238
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
239
- opacity: 0.8 + Math.random() * 0.2,
240
- thickness: mainThickness,
241
- lifetime: 0.4 + Math.random() * 0.2,
242
- age: 0,
243
- branches,
244
- revealDuration: 0.08 + Math.random() * 0.04,
245
- };
246
- };
247
- // Initialize lightning (empty array, lightning spawns dynamically)
248
- const initializeLightning = () => {
249
- return [];
419
+ },
420
+ });
421
+ if (!handle)
422
+ return;
423
+ handle.stage.dark = isDarkBackground(container);
424
+ scene =
425
+ type === "lightning"
426
+ ? lightningScene(handle.stage, count, palette.length)
427
+ : fallScene(handle.stage, type, count, palette.length, angle);
428
+ const run = {
429
+ scene,
430
+ handle,
431
+ motion,
432
+ showStill: (on) => {
433
+ // Lightning has no still frame: a held bolt reads as a glitch.
434
+ stillOn = on && type !== "lightning";
435
+ scene?.clear();
436
+ if (stillOn)
437
+ scene?.start(true);
438
+ handle.paint();
439
+ },
250
440
  };
251
- // Initialize particles only for mount trigger (manual/click handled by their respective handlers)
252
- // Only initialize if particles don't already exist to preserve active particles across re-renders
253
- if (particlesRef.current.length === 0) {
254
- const shouldInitialize = trigger === "mount";
255
- particlesRef.current = shouldInitialize
256
- ? type === "rain"
257
- ? initializeRain()
258
- : type === "snow"
259
- ? initializeSnow()
260
- : type === "leaves"
261
- ? initializeLeaves()
262
- : type === "lightning"
263
- ? initializeLightning()
264
- : []
265
- : [];
266
- }
267
- // Animation loop
268
- const angleRad = (angle * Math.PI) / 180; // Convert angle to radians
269
- const dx = Math.sin(angleRad); // Horizontal component
270
- const dy = Math.cos(angleRad); // Vertical component
271
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
272
- const animate = () => {
273
- timeRef.current += 0.016; // Approximate frame time
274
- ctx.clearRect(0, 0, canvasWidth, canvasHeight);
275
- // Check if we should still be emitting new particles
276
- const shouldEmit = trigger === "hover" ? isHoveredRef.current : isEmittingRef.current;
277
- // Check duration limit
278
- if (duration && isEmittingRef.current) {
279
- const elapsed = Date.now() - emitStartTimeRef.current;
280
- if (elapsed > duration) {
281
- isEmittingRef.current = false;
282
- }
441
+ runRef.current = run;
442
+ if (activeRef.current) {
443
+ startedRef.current = true;
444
+ if (motion) {
445
+ scene.start(true);
446
+ handle.wake();
283
447
  }
284
- if (type === "rain") {
285
- // Update and draw rain drops
286
- particlesRef.current.forEach((drop) => {
287
- // Update position with angle
288
- drop.y += drop.speed * dy;
289
- drop.x += drop.speed * dx;
290
- // Reset if it goes below canvas or off the sides (with expanded bounds)
291
- const leftBound = -horizontalOffset - 50;
292
- const rightBound = canvasWidth + horizontalOffset + 50;
293
- if (drop.y > canvasHeight || drop.x < leftBound || drop.x > rightBound) {
294
- if (shouldEmit) {
295
- // Respawn at top
296
- drop.y = -drop.length;
297
- const spawnWidth = canvasWidth + horizontalOffset * 2;
298
- drop.x = Math.random() * spawnWidth - horizontalOffset;
299
- }
300
- else {
301
- // Mark for removal by moving far off screen
302
- drop.y = canvasHeight + 1000;
303
- }
304
- }
305
- // Draw rain drop as an angled line with gradient
306
- const x1 = drop.x;
307
- const y1 = drop.y;
308
- const x2 = drop.x + dx * drop.length;
309
- const y2 = drop.y + dy * drop.length;
310
- // Create gradient from solid to transparent
311
- const gradient = ctx.createLinearGradient(x1, y1, x2, y2);
312
- gradient.addColorStop(0, "transparent");
313
- gradient.addColorStop(1, drop.color);
314
- ctx.beginPath();
315
- ctx.strokeStyle = gradient;
316
- ctx.globalAlpha = drop.opacity;
317
- ctx.lineWidth = drop.thickness;
318
- ctx.lineCap = "round";
319
- ctx.moveTo(x1, y1);
320
- ctx.lineTo(x2, y2);
321
- ctx.stroke();
322
- });
323
- }
324
- else if (type === "snow") {
325
- // Update and draw snowflakes
326
- particlesRef.current.forEach((flake) => {
327
- // Calculate sway motion (sine wave)
328
- const swayX = Math.sin(timeRef.current * flake.swaySpeed + flake.swayOffset) * flake.swayAmplitude;
329
- // Update position with angle and sway
330
- flake.y += flake.speed * dy;
331
- flake.x += flake.speed * dx;
332
- // Reset if it goes below canvas or off the sides
333
- const leftBound = -horizontalOffset - 100;
334
- const rightBound = canvasWidth + horizontalOffset + 100;
335
- if (flake.y > canvasHeight || flake.x < leftBound || flake.x > rightBound) {
336
- if (shouldEmit) {
337
- flake.y = -flake.size;
338
- const spawnWidth = canvasWidth + horizontalOffset * 2;
339
- flake.x = Math.random() * spawnWidth - horizontalOffset;
340
- }
341
- else {
342
- flake.y = canvasHeight + 1000;
343
- }
344
- }
345
- // Draw snowflake (no blur filter for performance)
346
- ctx.globalAlpha = flake.opacity;
347
- ctx.fillStyle = flake.color;
348
- // Draw as circle with sway applied
349
- ctx.beginPath();
350
- ctx.arc(flake.x + swayX, flake.y, flake.size / 2, 0, Math.PI * 2);
351
- ctx.fill();
352
- });
353
- }
354
- else if (type === "leaves") {
355
- // Update and draw leaves
356
- particlesRef.current.forEach((leaf) => {
357
- // Calculate sway motion
358
- const swayX = Math.sin(timeRef.current * leaf.swaySpeed + leaf.swayOffset) * leaf.swayAmplitude;
359
- // Update rotation (2D spin)
360
- leaf.rotation += leaf.rotationSpeed;
361
- // Update 3D rotation (flip/tumble)
362
- leaf.rotation3D += leaf.rotation3DSpeed;
363
- // Update position with angle and sway
364
- leaf.y += leaf.speed * dy;
365
- leaf.x += leaf.speed * dx;
366
- // Reset if it goes below canvas or off the sides
367
- const leftBound = -horizontalOffset - 100;
368
- const rightBound = canvasWidth + horizontalOffset + 100;
369
- if (leaf.y > canvasHeight || leaf.x < leftBound || leaf.x > rightBound) {
370
- if (shouldEmit) {
371
- leaf.y = -leaf.height;
372
- const spawnWidth = canvasWidth + horizontalOffset * 2;
373
- leaf.x = Math.random() * spawnWidth - horizontalOffset;
374
- leaf.rotation = Math.random() * Math.PI * 2;
375
- }
376
- else {
377
- leaf.y = canvasHeight + 1000;
378
- }
379
- }
380
- // Calculate 3D scale effect (flipping around vertical axis)
381
- const scaleXRaw = Math.cos(leaf.rotation3D);
382
- // Clamp scale to minimum 0.15 so leaves stay visible when edge-on
383
- const scaleX = scaleXRaw > 0 ? Math.max(0.15, scaleXRaw) : Math.min(-0.15, scaleXRaw);
384
- // Draw leaf with rotation and gradient
385
- ctx.save();
386
- ctx.translate(leaf.x + swayX, leaf.y);
387
- ctx.rotate(leaf.rotation);
388
- ctx.scale(scaleX, 1); // Apply 3D flip effect with minimum width
389
- // Fade when edge-on but maintain minimum 50% opacity
390
- const opacityMultiplier = Math.max(0.5, Math.abs(scaleXRaw * 0.3 + 0.7));
391
- ctx.globalAlpha = leaf.opacity * opacityMultiplier;
392
- // Create gradient from color1 to color2
393
- const gradient = ctx.createLinearGradient(-leaf.width / 2, 0, leaf.width / 2, 0);
394
- gradient.addColorStop(0, leaf.color1);
395
- gradient.addColorStop(0.5, leaf.color2);
396
- gradient.addColorStop(1, leaf.color1);
397
- // Draw leaf shape (pointed oval using bezier curves)
398
- ctx.fillStyle = gradient;
399
- ctx.beginPath();
400
- const w = leaf.width / 2;
401
- const h = leaf.height / 2;
402
- // Start at top tip
403
- ctx.moveTo(0, -h);
404
- // Curve to right side (widest point)
405
- ctx.bezierCurveTo(w * 0.7, -h * 0.5, w * 0.7, h * 0.5, 0, h);
406
- // Curve to left side and back to top
407
- ctx.bezierCurveTo(-w * 0.7, h * 0.5, -w * 0.7, -h * 0.5, 0, -h);
408
- ctx.fill();
409
- ctx.restore();
410
- });
411
- }
412
- else if (type === "lightning") {
413
- // Lightning spawning logic
414
- const currentTime = Date.now();
415
- const timeSinceLastLightning = (currentTime - lastLightningTimeRef.current) / 1000;
416
- // Reduced frequency: intensity 1 = ~15s, intensity 10 = ~3s, intensity 50 = ~0.6s, intensity 100 = ~0.3s
417
- const spawnInterval = Math.max(0.3, 15 / intensity);
418
- if (shouldEmit && timeSinceLastLightning > spawnInterval) {
419
- // Calculate number of simultaneous bolts based on intensity
420
- // After a multi-bolt strike, force a single bolt for variation
421
- let boltCount = 1;
422
- if (lastBoltCountRef.current > 1) {
423
- // Previous strike was multi-bolt, do single bolt this time
424
- boltCount = 1;
425
- }
426
- else {
427
- // Previous was single, can do multi-bolt based on intensity
428
- if (intensity > 60) {
429
- // 60% chance of multi-bolt at high intensity
430
- boltCount = Math.random() < 0.6 ? 2 + Math.floor(Math.random() * 3) : 1; // 2-4 bolts or 1
431
- }
432
- else if (intensity > 30) {
433
- // 50% chance of multi-bolt at medium intensity
434
- boltCount = Math.random() < 0.5 ? 2 + Math.floor(Math.random() * 2) : 1; // 2-3 bolts or 1
435
- }
436
- else if (intensity > 15) {
437
- // 30% chance of double bolt at low-medium intensity
438
- boltCount = Math.random() < 0.3 ? 2 : 1;
439
- }
440
- // intensity <= 15: always single bolt
441
- }
442
- // Store bolt count for next iteration
443
- lastBoltCountRef.current = boltCount;
444
- // Spawn multiple bolts with slight time offset for realism
445
- for (let i = 0; i < boltCount; i++) {
446
- const startX = Math.random() * canvasWidth;
447
- const bolt = generateLightningBolt(startX, 0, canvasHeight);
448
- // Add slight age offset for staggered appearance
449
- bolt.age = -i * 0.025; // 25ms offset between bolts
450
- particlesRef.current.push(bolt);
451
- }
452
- lastLightningTimeRef.current = currentTime;
453
- }
454
- // Update and draw lightning bolts
455
- particlesRef.current.forEach((bolt, index) => {
456
- bolt.age += 0.016; // Increment age
457
- // Skip if not yet started (negative age for staggered bolts)
458
- if (bolt.age < 0)
459
- return;
460
- // Remove expired bolts
461
- if (bolt.age > bolt.lifetime) {
462
- particlesRef.current.splice(index, 1);
463
- return;
464
- }
465
- // Calculate reveal progress (how much of the bolt to draw)
466
- const revealProgress = Math.min(1, bolt.age / bolt.revealDuration);
467
- // Calculate opacity fade (flash effect)
468
- const lifeProgress = bolt.age / bolt.lifetime;
469
- let currentOpacity = bolt.opacity;
470
- // During reveal: full brightness
471
- // After reveal: hold briefly, then fade out
472
- if (lifeProgress < bolt.revealDuration / bolt.lifetime) {
473
- currentOpacity *= revealProgress; // Fade in during reveal
474
- }
475
- else if (lifeProgress < 0.3) {
476
- currentOpacity *= 1; // Hold at full brightness
477
- }
478
- else {
479
- // Fade out in the remaining time
480
- const fadeProgress = (lifeProgress - 0.3) / 0.7;
481
- currentOpacity *= 1 - fadeProgress;
482
- }
483
- // Calculate how many segments to draw based on reveal progress
484
- const totalSegments = bolt.segments.length;
485
- const segmentsToDraw = Math.ceil(totalSegments * revealProgress);
486
- // Draw main bolt with reveal effect
487
- ctx.globalAlpha = currentOpacity;
488
- ctx.strokeStyle = bolt.color;
489
- ctx.lineWidth = bolt.thickness;
490
- ctx.lineCap = "round";
491
- ctx.lineJoin = "round";
492
- // Draw glow effect
493
- ctx.shadowBlur = 15;
494
- ctx.shadowColor = bolt.color;
495
- ctx.beginPath();
496
- for (let i = 0; i < segmentsToDraw; i++) {
497
- const segment = bolt.segments[i];
498
- if (i === 0) {
499
- ctx.moveTo(segment.x, segment.y);
500
- }
501
- else {
502
- ctx.lineTo(segment.x, segment.y);
503
- }
504
- }
505
- ctx.stroke();
506
- // Recursive function to draw hierarchical branches
507
- const drawBranch = (branch, parentSegments, parentSegmentsToDraw) => {
508
- // Only draw if parent bolt has reached this branch point
509
- if (branch.startIndex < parentSegmentsToDraw) {
510
- const startSegment = parentSegments[branch.startIndex];
511
- // Calculate how much of this branch to reveal
512
- const segmentsPastBranch = parentSegmentsToDraw - branch.startIndex;
513
- const branchRevealProgress = Math.min(1, segmentsPastBranch / 3);
514
- const branchSegmentsToDraw = Math.ceil(branch.segments.length * branchRevealProgress);
515
- // Draw this branch
516
- ctx.beginPath();
517
- ctx.moveTo(startSegment.x, startSegment.y);
518
- for (let i = 0; i < branchSegmentsToDraw; i++) {
519
- const segment = branch.segments[i];
520
- ctx.lineTo(segment.x, segment.y);
521
- }
522
- ctx.lineWidth = branch.thickness;
523
- ctx.stroke();
524
- // Recursively draw child branches
525
- if (branch.children && branch.children.length > 0) {
526
- branch.children.forEach((childBranch) => {
527
- drawBranch(childBranch, branch.segments, branchSegmentsToDraw);
528
- });
529
- }
530
- }
531
- };
532
- // Draw all primary branches and their hierarchies
533
- bolt.branches.forEach((branch) => {
534
- drawBranch(branch, bolt.segments, segmentsToDraw);
535
- });
536
- // Reset shadow
537
- ctx.shadowBlur = 0;
538
- });
448
+ else {
449
+ run.showStill(true);
539
450
  }
540
- ctx.globalAlpha = 1;
541
- animationRef.current = requestAnimationFrame(animate);
542
- };
543
- if (!shouldAnimate) {
544
- // When reduced motion is active, don't start the animation loop at all
545
- return () => {
546
- window.removeEventListener("resize", updateSize);
547
- };
548
451
  }
549
- animate();
452
+ else {
453
+ startedRef.current = false;
454
+ }
455
+ const unwatch = watchTheme(() => {
456
+ palette = colors.map((c) => canvasColor(container, c));
457
+ handle.stage.dark = isDarkBackground(container);
458
+ sprites = spriteCache();
459
+ if (!motion)
460
+ handle.paint();
461
+ });
550
462
  return () => {
551
- window.removeEventListener("resize", updateSize);
552
- if (animationRef.current) {
553
- cancelAnimationFrame(animationRef.current);
554
- }
463
+ unwatch();
464
+ handle.stop();
465
+ if (runRef.current === run)
466
+ runRef.current = null;
555
467
  };
556
- }, [type, colors, speed, intensity, angle, duration, trigger, shouldAnimate]);
557
- // Respond to external control in manual mode
468
+ }, [type, colorsKey, speed, count, angle, reducedMotion, shouldAnimate]);
469
+ // `active` turning on lets the weather in from above; turning off lets it fall away.
558
470
  useEffect(() => {
559
- if (trigger !== "manual")
471
+ const run = runRef.current;
472
+ if (!run)
560
473
  return;
561
- if (active && !isEmittingRef.current) {
562
- // Initialize particles if starting emission
563
- if (particlesRef.current.length === 0) {
564
- const canvas = canvasRef.current;
565
- const container = containerRef.current;
566
- if (canvas && container) {
567
- const canvasWidth = canvas.width / 2;
568
- const canvasHeight = canvas.height / 2;
569
- const parsedColors = colors.map((color) => {
570
- const computedColor = getComputedStyle(container).getPropertyValue(`--${color}`);
571
- return computedColor || color;
572
- });
573
- if (type === "rain") {
574
- const particles = [];
575
- const angleRad = (angle * Math.PI) / 180;
576
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
577
- for (let i = 0; i < intensity; i++) {
578
- const spawnWidth = canvasWidth + horizontalOffset * 2;
579
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
580
- particles.push({
581
- x: spawnX,
582
- y: Math.random() * canvasHeight - canvasHeight,
583
- length: 10 + Math.random() * 20,
584
- speed: (2 + Math.random() * 3) * speed,
585
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
586
- opacity: 0.3 + Math.random() * 0.5,
587
- thickness: 1 + Math.random() * 1.5,
588
- });
589
- }
590
- particlesRef.current = particles;
591
- }
592
- else if (type === "snow") {
593
- const particles = [];
594
- const angleRad = (angle * Math.PI) / 180;
595
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
596
- for (let i = 0; i < intensity; i++) {
597
- const depth = Math.random();
598
- const size = 2 + depth * 4;
599
- const spawnWidth = canvasWidth + horizontalOffset * 2;
600
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
601
- particles.push({
602
- x: spawnX,
603
- y: Math.random() * canvasHeight - canvasHeight,
604
- size,
605
- speed: (0.3 + depth * 0.7) * speed,
606
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
607
- opacity: 0.4 + depth * 0.5,
608
- swayAmplitude: 20 + Math.random() * 30,
609
- swaySpeed: 0.5 + Math.random() * 1,
610
- swayOffset: Math.random() * Math.PI * 2,
611
- depth,
612
- });
613
- }
614
- particlesRef.current = particles;
615
- }
616
- else if (type === "leaves") {
617
- const particles = [];
618
- const angleRad = (angle * Math.PI) / 180;
619
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
620
- for (let i = 0; i < intensity; i++) {
621
- const depth = Math.random();
622
- const width = 8 + depth * 12;
623
- const height = width * (0.6 + Math.random() * 0.4);
624
- const spawnWidth = canvasWidth + horizontalOffset * 2;
625
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
626
- const colorIndex = Math.floor(Math.random() * parsedColors.length);
627
- const color1 = parsedColors[colorIndex];
628
- const color2 = parsedColors[Math.min(colorIndex + 1, parsedColors.length - 1)];
629
- particles.push({
630
- x: spawnX,
631
- y: Math.random() * canvasHeight - canvasHeight,
632
- width,
633
- height,
634
- speed: (0.4 + depth * 0.8) * speed,
635
- color1,
636
- color2,
637
- opacity: 0.6 + depth * 0.3,
638
- swayAmplitude: 30 + Math.random() * 50,
639
- swaySpeed: 0.3 + Math.random() * 0.7,
640
- swayOffset: Math.random() * Math.PI * 2,
641
- rotation: Math.random() * Math.PI * 2,
642
- rotationSpeed: (Math.random() - 0.5) * 0.08,
643
- rotation3D: Math.random() * Math.PI * 2,
644
- rotation3DSpeed: (Math.random() - 0.5) * 0.06,
645
- depth,
646
- });
647
- }
648
- particlesRef.current = particles;
649
- }
650
- }
474
+ if (active && !startedRef.current) {
475
+ startedRef.current = true;
476
+ if (run.motion) {
477
+ run.scene.start(false);
478
+ run.handle.wake();
651
479
  }
652
- isEmittingRef.current = true;
653
- emitStartTimeRef.current = Date.now();
654
- }
655
- else if (!active && isEmittingRef.current) {
656
- isEmittingRef.current = false;
657
- }
658
- }, [active, trigger]);
659
- const handleMouseEnter = () => {
660
- if (trigger === "hover" && !isHoveredRef.current) {
661
- isHoveredRef.current = true;
662
- isEmittingRef.current = true;
663
- emitStartTimeRef.current = Date.now();
664
- // Initialize particles if none exist yet
665
- if (particlesRef.current.length === 0) {
666
- const canvas = canvasRef.current;
667
- const container = containerRef.current;
668
- if (canvas && container) {
669
- const cw = canvas.width / 2;
670
- const ch = canvas.height / 2;
671
- const parsedColors = colors.map((color) => {
672
- const computedColor = getComputedStyle(container).getPropertyValue(`--${color}`);
673
- return computedColor || color;
674
- });
675
- const angleRad = (angle * Math.PI) / 180;
676
- const horizontalOffset = Math.abs(Math.tan(angleRad) * ch);
677
- if (type === "rain") {
678
- const particles = [];
679
- for (let i = 0; i < intensity; i++) {
680
- const spawnWidth = cw + horizontalOffset * 2;
681
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
682
- particles.push({
683
- x: spawnX,
684
- y: Math.random() * ch - ch,
685
- length: 10 + Math.random() * 20,
686
- speed: (2 + Math.random() * 3) * speed,
687
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
688
- opacity: 0.3 + Math.random() * 0.5,
689
- thickness: 1 + Math.random() * 1.5,
690
- });
691
- }
692
- particlesRef.current = particles;
693
- }
694
- else if (type === "snow") {
695
- const particles = [];
696
- for (let i = 0; i < intensity; i++) {
697
- const depth = Math.random();
698
- const size = 2 + depth * 4;
699
- const spawnWidth = cw + horizontalOffset * 2;
700
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
701
- particles.push({
702
- x: spawnX,
703
- y: Math.random() * ch - ch,
704
- size,
705
- speed: (0.3 + depth * 0.7) * speed,
706
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
707
- opacity: 0.4 + depth * 0.5,
708
- swayAmplitude: 20 + Math.random() * 30,
709
- swaySpeed: 0.5 + Math.random() * 1,
710
- swayOffset: Math.random() * Math.PI * 2,
711
- depth,
712
- });
713
- }
714
- particlesRef.current = particles;
715
- }
716
- else if (type === "leaves") {
717
- const particles = [];
718
- for (let i = 0; i < intensity; i++) {
719
- const depth = Math.random();
720
- const width = 8 + depth * 12;
721
- const height = width * (0.6 + Math.random() * 0.4);
722
- const spawnWidth = cw + horizontalOffset * 2;
723
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
724
- const colorIndex = Math.floor(Math.random() * parsedColors.length);
725
- const color1 = parsedColors[colorIndex];
726
- const color2 = parsedColors[Math.min(colorIndex + 1, parsedColors.length - 1)];
727
- particles.push({
728
- x: spawnX,
729
- y: Math.random() * ch - ch,
730
- width,
731
- height,
732
- speed: (0.4 + depth * 0.8) * speed,
733
- color1,
734
- color2,
735
- opacity: 0.6 + depth * 0.3,
736
- swayAmplitude: 30 + Math.random() * 50,
737
- swaySpeed: 0.3 + Math.random() * 0.7,
738
- swayOffset: Math.random() * Math.PI * 2,
739
- rotation: Math.random() * Math.PI * 2,
740
- rotationSpeed: (Math.random() - 0.5) * 0.08,
741
- rotation3D: Math.random() * Math.PI * 2,
742
- rotation3DSpeed: (Math.random() - 0.5) * 0.06,
743
- depth,
744
- });
745
- }
746
- particlesRef.current = particles;
747
- }
748
- // Lightning doesn't need pre-initialization (spawns dynamically)
749
- }
480
+ else {
481
+ run.showStill(true);
750
482
  }
751
483
  }
752
- };
753
- const handleMouseLeave = () => {
754
- if (trigger === "hover" && isHoveredRef.current) {
755
- isHoveredRef.current = false;
484
+ else if (!active && startedRef.current) {
485
+ startedRef.current = false;
486
+ if (!run.motion)
487
+ run.showStill(false);
756
488
  }
757
- };
758
- const handleClick = () => {
759
- if (trigger !== "click")
489
+ }, [active]);
490
+ useEffect(() => {
491
+ if (!active || duration === undefined || !(duration > 0) || !Number.isFinite(duration))
760
492
  return;
761
- if (!isEmittingRef.current) {
762
- // Initialize particles if starting emission
763
- if (particlesRef.current.length === 0) {
764
- const canvas = canvasRef.current;
765
- const container = containerRef.current;
766
- if (canvas && container) {
767
- const canvasWidth = canvas.width / 2;
768
- const canvasHeight = canvas.height / 2;
769
- const parsedColors = colors.map((color) => {
770
- const computedColor = getComputedStyle(container).getPropertyValue(`--${color}`);
771
- return computedColor || color;
772
- });
773
- if (type === "rain") {
774
- const particles = [];
775
- const angleRad = (angle * Math.PI) / 180;
776
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
777
- for (let i = 0; i < intensity; i++) {
778
- const spawnWidth = canvasWidth + horizontalOffset * 2;
779
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
780
- particles.push({
781
- x: spawnX,
782
- y: Math.random() * canvasHeight - canvasHeight,
783
- length: 10 + Math.random() * 20,
784
- speed: (2 + Math.random() * 3) * speed,
785
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
786
- opacity: 0.3 + Math.random() * 0.5,
787
- thickness: 1 + Math.random() * 1.5,
788
- });
789
- }
790
- particlesRef.current = particles;
791
- }
792
- else if (type === "snow") {
793
- const particles = [];
794
- const angleRad = (angle * Math.PI) / 180;
795
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
796
- for (let i = 0; i < intensity; i++) {
797
- const depth = Math.random();
798
- const size = 2 + depth * 4;
799
- const spawnWidth = canvasWidth + horizontalOffset * 2;
800
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
801
- particles.push({
802
- x: spawnX,
803
- y: Math.random() * canvasHeight - canvasHeight,
804
- size,
805
- speed: (0.3 + depth * 0.7) * speed,
806
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
807
- opacity: 0.4 + depth * 0.5,
808
- swayAmplitude: 20 + Math.random() * 30,
809
- swaySpeed: 0.5 + Math.random() * 1,
810
- swayOffset: Math.random() * Math.PI * 2,
811
- depth,
812
- });
813
- }
814
- particlesRef.current = particles;
815
- }
816
- else if (type === "leaves") {
817
- const particles = [];
818
- const angleRad = (angle * Math.PI) / 180;
819
- const horizontalOffset = Math.abs(Math.tan(angleRad) * canvasHeight);
820
- for (let i = 0; i < intensity; i++) {
821
- const depth = Math.random();
822
- const width = 8 + depth * 12;
823
- const height = width * (0.6 + Math.random() * 0.4);
824
- const spawnWidth = canvasWidth + horizontalOffset * 2;
825
- const spawnX = Math.random() * spawnWidth - horizontalOffset;
826
- const colorIndex = Math.floor(Math.random() * parsedColors.length);
827
- const color1 = parsedColors[colorIndex];
828
- const color2 = parsedColors[Math.min(colorIndex + 1, parsedColors.length - 1)];
829
- particles.push({
830
- x: spawnX,
831
- y: Math.random() * canvasHeight - canvasHeight,
832
- width,
833
- height,
834
- speed: (0.4 + depth * 0.8) * speed,
835
- color1,
836
- color2,
837
- opacity: 0.6 + depth * 0.3,
838
- swayAmplitude: 30 + Math.random() * 50,
839
- swaySpeed: 0.3 + Math.random() * 0.7,
840
- swayOffset: Math.random() * Math.PI * 2,
841
- rotation: Math.random() * Math.PI * 2,
842
- rotationSpeed: (Math.random() - 0.5) * 0.08,
843
- rotation3D: Math.random() * Math.PI * 2,
844
- rotation3DSpeed: (Math.random() - 0.5) * 0.06,
845
- depth,
846
- });
847
- }
848
- particlesRef.current = particles;
849
- }
850
- }
851
- }
852
- isEmittingRef.current = true;
853
- emitStartTimeRef.current = Date.now();
854
- }
855
- else {
856
- isEmittingRef.current = false;
857
- }
493
+ const timer = setTimeout(() => setActive(false), duration);
494
+ return () => clearTimeout(timer);
495
+ }, [active, duration, setActive]);
496
+ const hoverIsTap = trigger === "hover" && cannotHover();
497
+ const handleMouseEnter = (event) => {
498
+ onMouseEnter?.(event);
499
+ if (trigger === "hover" && !hoverIsTap)
500
+ setActive(true);
501
+ };
502
+ const handleMouseLeave = (event) => {
503
+ onMouseLeave?.(event);
504
+ if (trigger === "hover" && !hoverIsTap)
505
+ setActive(false);
506
+ };
507
+ const handleClick = (event) => {
508
+ onClick?.(event);
509
+ if (trigger === "click" || hoverIsTap)
510
+ setActive((on) => !on);
858
511
  };
859
512
  return (_jsxs(Flex, { ref: containerRef, fill: true, overflow: "hidden", onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onClick: handleClick, ...rest, children: [_jsx("canvas", { ref: canvasRef, "aria-hidden": "true", style: {
860
513
  position: "absolute",