@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.
@@ -2,19 +2,331 @@
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 CelebrationFx = ({ ref: forwardedRef, type = "confetti", speed: speedProp, colors = ["brand-solid-medium", "accent-solid-medium"], intensity = 50, duration, trigger = "mount", active = true, reducedMotion = "auto", children, style, ...rest }) => {
9
+ import { useControllableState } from "./internal/useControllableState.js";
10
+ const DEFAULT_COLORS = [
11
+ "brand-solid-medium",
12
+ "accent-solid-medium",
13
+ "brand-on-background-medium",
14
+ "accent-on-background-medium",
15
+ ];
16
+ const DEFAULT_FIREWORK_COLORS = [
17
+ "brand-solid-strong",
18
+ "accent-solid-strong",
19
+ "brand-solid-medium",
20
+ "accent-solid-medium",
21
+ ];
22
+ const SHAPES = 3; // ribbon, square, circle
23
+ const MAX_CONFETTI = 700;
24
+ const GRAVITY = 520; // px/s²
25
+ const AIR = 3.2; // confetti drag, 1/s; terminal fall ≈ GRAVITY / AIR
26
+ function confettiScene(stage, count, colorCount) {
27
+ let pieces = [];
28
+ let rainDebt = 0;
29
+ const piece = (x, y, vx, vy) => {
30
+ const shape = pick(SHAPES);
31
+ const size = rand(6, 11);
32
+ return {
33
+ x,
34
+ y,
35
+ vx,
36
+ vy,
37
+ w: shape === 0 ? size * 0.45 : size,
38
+ h: shape === 0 ? size * 1.5 : size,
39
+ rot: rand(0, Math.PI * 2),
40
+ vrot: rand(-5, 5),
41
+ flip: rand(0, Math.PI * 2),
42
+ vflip: rand(5, 11) * (Math.random() < 0.5 ? -1 : 1),
43
+ sway: rand(0, Math.PI * 2),
44
+ vsway: rand(2, 4),
45
+ color: pick(colorCount),
46
+ shape,
47
+ };
48
+ };
49
+ const add = (p) => {
50
+ if (pieces.length < MAX_CONFETTI)
51
+ pieces.push(p);
52
+ };
53
+ // Launch speed that carries a piece most of the way up through the drag.
54
+ const reach = () => AIR * Math.min(stage.height, 900) * rand(0.6, 1.1);
55
+ const start = () => {
56
+ const { width, height } = stage;
57
+ for (let i = 0; i < count; i++) {
58
+ for (const side of [0, 1]) {
59
+ // Up and inwards from each bottom corner.
60
+ const angle = -rand(Math.PI * 0.22, Math.PI * 0.45);
61
+ const v = reach();
62
+ const vx = Math.cos(angle) * v * (side === 0 ? 1 : -1);
63
+ const vy = Math.sin(angle) * v;
64
+ add(piece(side === 0 ? rand(-8, 8) : width + rand(-8, 8), height + rand(0, 12), vx, vy));
65
+ }
66
+ }
67
+ };
68
+ const burst = (x, y) => {
69
+ const n = Math.max(12, Math.round(count * 0.8));
70
+ for (let i = 0; i < n; i++) {
71
+ const angle = rand(0, Math.PI * 2);
72
+ const v = rand(0.25, 0.6) * reach();
73
+ add(piece(x, y, Math.cos(angle) * v, Math.sin(angle) * v - v * 0.6));
74
+ }
75
+ };
76
+ const step = (dt, emitting) => {
77
+ const { width, height } = stage;
78
+ if (emitting && dt > 0) {
79
+ // A light fall from above keeps the air full while the celebration runs.
80
+ rainDebt += dt * count * 0.5;
81
+ while (rainDebt >= 1) {
82
+ rainDebt -= 1;
83
+ add(piece(rand(0, width), rand(-24, -8), rand(-30, 30), rand(30, 90)));
84
+ }
85
+ }
86
+ const drag = Math.exp(-AIR * dt);
87
+ let alive = 0;
88
+ for (const p of pieces) {
89
+ p.vy += GRAVITY * dt;
90
+ p.vx *= drag;
91
+ p.vy *= drag;
92
+ p.x += p.vx * dt;
93
+ p.y += p.vy * dt;
94
+ p.rot += p.vrot * dt;
95
+ p.flip += p.vflip * dt;
96
+ p.sway += p.vsway * dt;
97
+ if (p.y < height + 24)
98
+ pieces[alive++] = p;
99
+ }
100
+ pieces.length = alive;
101
+ };
102
+ const draw = (colors) => {
103
+ const { ctx, dpr } = stage;
104
+ for (const p of pieces) {
105
+ const cosFlip = Math.cos(p.flip);
106
+ // Paper turning over: thin when edge-on, darker on its back.
107
+ const sy = cosFlip >= 0 ? Math.max(0.12, cosFlip) : Math.min(-0.12, cosFlip);
108
+ const cos = Math.cos(p.rot);
109
+ const sin = Math.sin(p.rot);
110
+ const x = p.x + Math.sin(p.sway) * 4 * Math.min(1, Math.abs(p.vy) / 60 + 0.2);
111
+ ctx.setTransform(dpr * cos, dpr * sin, -dpr * sin * sy, dpr * cos * sy, dpr * x, dpr * p.y);
112
+ ctx.globalAlpha = 0.55 + 0.45 * Math.abs(cosFlip);
113
+ ctx.fillStyle = colors[p.color] ?? colors[0];
114
+ if (p.shape === 2) {
115
+ ctx.beginPath();
116
+ ctx.arc(0, 0, p.w / 2, 0, Math.PI * 2);
117
+ ctx.fill();
118
+ }
119
+ else {
120
+ ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
121
+ }
122
+ }
123
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
124
+ };
125
+ const still = (x, y) => {
126
+ const { width, height } = stage;
127
+ const n = x === undefined ? count * 2 : Math.max(12, Math.round(count * 0.8));
128
+ pieces = [];
129
+ for (let i = 0; i < n; i++) {
130
+ const p = x === undefined || y === undefined
131
+ ? piece(rand(0, width), rand(0, height), 0, 0)
132
+ : piece(x + rand(-1, 1) * 70, y + rand(-1, 1) * 50, 0, 0);
133
+ add(p);
134
+ }
135
+ };
136
+ return {
137
+ start,
138
+ burst,
139
+ step,
140
+ draw,
141
+ still,
142
+ alive: () => pieces.length > 0,
143
+ clear: () => {
144
+ pieces = [];
145
+ },
146
+ };
147
+ }
148
+ function fireworksScene(stage, count, colorCount) {
149
+ let rockets = [];
150
+ let sparks = [];
151
+ let flashes = [];
152
+ let nextLaunch = 0;
153
+ const sparkCount = 24 + Math.round(count * 0.6);
154
+ const ROCKET_G = 420;
155
+ const SPARK_G = 150;
156
+ const SPARK_DRAG = 1.9;
157
+ const launch = (delay = 0) => {
158
+ const { width, height } = stage;
159
+ const target = height * rand(0.18, 0.45);
160
+ const y = height + 4 + delay * 600;
161
+ rockets.push({
162
+ x: width * rand(0.18, 0.82),
163
+ y,
164
+ vy: -Math.sqrt(2 * ROCKET_G * Math.max(40, y - target)),
165
+ color: pick(colorCount),
166
+ });
167
+ };
168
+ const explode = (x, y, color, age = 0) => {
169
+ const size = Math.max(110, Math.min(380, Math.min(stage.width, stage.height) * 0.85));
170
+ for (let i = 0; i < sparkCount; i++) {
171
+ const angle = (Math.PI * 2 * i) / sparkCount + rand(-0.08, 0.08);
172
+ const v = size * rand(0.7, 1) * (Math.random() < 0.15 ? 0.55 : 1);
173
+ sparks.push({
174
+ x,
175
+ y,
176
+ vx: Math.cos(angle) * v,
177
+ vy: Math.sin(angle) * v,
178
+ age,
179
+ life: rand(0.9, 1.5),
180
+ color: Math.random() < 0.2 ? pick(colorCount) : color,
181
+ size: rand(1.6, 2.6),
182
+ });
183
+ }
184
+ flashes.push({ x, y, age, color });
185
+ };
186
+ const stepSparks = (dt) => {
187
+ const drag = Math.exp(-SPARK_DRAG * dt);
188
+ let n = 0;
189
+ for (const s of sparks) {
190
+ s.age += dt;
191
+ s.vx *= drag;
192
+ s.vy = s.vy * drag + SPARK_G * dt;
193
+ s.x += s.vx * dt;
194
+ s.y += s.vy * dt;
195
+ if (s.age < s.life)
196
+ sparks[n++] = s;
197
+ }
198
+ sparks.length = n;
199
+ };
200
+ const step = (dt, emitting) => {
201
+ if (emitting && dt > 0) {
202
+ nextLaunch -= dt;
203
+ if (nextLaunch <= 0) {
204
+ launch();
205
+ nextLaunch = rand(0.45, 0.95);
206
+ }
207
+ }
208
+ let r = 0;
209
+ for (const rocket of rockets) {
210
+ rocket.vy += ROCKET_G * dt;
211
+ rocket.y += rocket.vy * dt;
212
+ if (rocket.vy >= -40)
213
+ explode(rocket.x, rocket.y, rocket.color);
214
+ else
215
+ rockets[r++] = rocket;
216
+ }
217
+ rockets.length = r;
218
+ stepSparks(dt);
219
+ flashes = flashes.filter((f) => {
220
+ f.age += dt;
221
+ return f.age < 0.18;
222
+ });
223
+ };
224
+ const draw = (colors) => {
225
+ const { ctx } = stage;
226
+ const color = (i) => colors[i] ?? colors[0];
227
+ // Light adds up on a dark page; on a light page it would wash out.
228
+ ctx.globalCompositeOperation = stage.dark ? "lighter" : "source-over";
229
+ ctx.lineCap = "round";
230
+ for (const f of flashes) {
231
+ const t = f.age / 0.18;
232
+ const radius = 18 + t * 46;
233
+ const glow = ctx.createRadialGradient(f.x, f.y, 0, f.x, f.y, radius);
234
+ glow.addColorStop(0, color(f.color));
235
+ glow.addColorStop(1, "transparent");
236
+ ctx.globalAlpha = 0.45 * (1 - t);
237
+ ctx.fillStyle = glow;
238
+ ctx.fillRect(f.x - radius, f.y - radius, radius * 2, radius * 2);
239
+ }
240
+ for (const rocket of rockets) {
241
+ ctx.globalAlpha = 0.9;
242
+ ctx.strokeStyle = color(rocket.color);
243
+ ctx.lineWidth = 2;
244
+ ctx.beginPath();
245
+ ctx.moveTo(rocket.x, rocket.y);
246
+ ctx.lineTo(rocket.x, rocket.y - rocket.vy * 0.06);
247
+ ctx.stroke();
248
+ ctx.globalAlpha = 0.3;
249
+ ctx.beginPath();
250
+ ctx.moveTo(rocket.x, rocket.y - rocket.vy * 0.06);
251
+ ctx.lineTo(rocket.x, rocket.y - rocket.vy * 0.16);
252
+ ctx.stroke();
253
+ }
254
+ for (const s of sparks) {
255
+ const t = s.age / s.life;
256
+ let alpha = (1 - t) ** 1.3;
257
+ // Crackle as the shell burns out.
258
+ if (t > 0.7)
259
+ alpha *= 0.4 + 0.6 * Math.random();
260
+ ctx.globalAlpha = alpha;
261
+ ctx.strokeStyle = color(s.color);
262
+ ctx.lineWidth = s.size;
263
+ ctx.beginPath();
264
+ ctx.moveTo(s.x - s.vx * 0.07, s.y - s.vy * 0.07);
265
+ ctx.lineTo(s.x, s.y);
266
+ ctx.stroke();
267
+ // A white-hot head while the shell is young.
268
+ if (stage.dark && t < 0.35) {
269
+ ctx.globalAlpha = (1 - t / 0.35) * 0.8;
270
+ ctx.fillStyle = "#fff";
271
+ ctx.fillRect(s.x - s.size * 0.5, s.y - s.size * 0.5, s.size, s.size);
272
+ }
273
+ }
274
+ ctx.globalCompositeOperation = "source-over";
275
+ };
276
+ const still = (x, y) => {
277
+ rockets = [];
278
+ sparks = [];
279
+ flashes = [];
280
+ const { width, height } = stage;
281
+ const shells = x === undefined || y === undefined
282
+ ? [
283
+ [width * 0.3, height * 0.35],
284
+ [width * 0.7, height * 0.3],
285
+ ]
286
+ : [[x, y]];
287
+ for (const [sx, sy] of shells) {
288
+ explode(sx, sy, pick(colorCount));
289
+ }
290
+ // Lay the sparks out where they are a third of the way through, with no motion after.
291
+ for (let i = 0; i < 20; i++)
292
+ stepSparks(0.02);
293
+ flashes = [];
294
+ };
295
+ return {
296
+ start: () => {
297
+ launch();
298
+ launch(0.25);
299
+ nextLaunch = rand(0.6, 0.9);
300
+ },
301
+ burst: (x, y) => explode(x, y, pick(colorCount)),
302
+ step,
303
+ draw,
304
+ still,
305
+ alive: () => rockets.length + sparks.length + flashes.length > 0,
306
+ clear: () => {
307
+ rockets = [];
308
+ sparks = [];
309
+ flashes = [];
310
+ },
311
+ };
312
+ }
313
+ const CelebrationFx = ({ ref: forwardedRef, type = "confetti", speed: speedProp, colors: colorsProp, intensity = 50, duration = 3000, trigger = "mount", active: activeProp, defaultActive, onActiveChange, reducedMotion = "auto", children, onClick, onMouseEnter, onMouseLeave, ...rest }) => {
7
314
  const speed = speedFactor(speedProp);
315
+ const colors = colorsProp ?? (type === "fireworks" ? DEFAULT_FIREWORK_COLORS : DEFAULT_COLORS);
316
+ const count = clampCount(intensity, 200);
317
+ const colorsKey = colors.join("|");
8
318
  const { shouldAnimate } = useReducedMotion(reducedMotion);
319
+ const [active, setActive] = useControllableState({
320
+ value: activeProp,
321
+ defaultValue: defaultActive ?? trigger === "mount",
322
+ onChange: onActiveChange,
323
+ });
9
324
  const containerRef = useRef(null);
10
325
  const canvasRef = useRef(null);
11
- const animationRef = useRef(undefined);
12
- const particlesRef = useRef([]);
13
- const isEmittingRef = useRef(trigger === "mount");
14
- const emitStartTimeRef = useRef(Date.now());
15
- const isHoveredRef = useRef(false);
16
- const fireworkTimerRef = useRef(0);
17
- const clickPositionRef = useRef(null);
326
+ const activeRef = useRef(active);
327
+ activeRef.current = active;
328
+ const startedRef = useRef(false);
329
+ const runRef = useRef(null);
18
330
  useEffect(() => {
19
331
  if (forwardedRef) {
20
332
  if ("current" in forwardedRef) {
@@ -25,288 +337,148 @@ const CelebrationFx = ({ ref: forwardedRef, type = "confetti", speed: speedProp,
25
337
  }
26
338
  }
27
339
  }, [forwardedRef]);
28
- // Handle manual trigger
29
- useEffect(() => {
30
- if (trigger === "manual") {
31
- if (active) {
32
- isEmittingRef.current = true;
33
- emitStartTimeRef.current = Date.now();
34
- }
35
- else {
36
- isEmittingRef.current = false;
37
- }
38
- }
39
- }, [trigger, active]);
340
+ // One scene per look: a new type, palette, pace or amount starts afresh.
341
+ // biome-ignore lint/correctness/useExhaustiveDependencies: colorsKey stands for colors
40
342
  useEffect(() => {
41
343
  const canvas = canvasRef.current;
42
344
  const container = containerRef.current;
43
345
  if (!canvas || !container)
44
346
  return;
45
- const ctx = canvas.getContext("2d");
46
- if (!ctx)
347
+ const motion = reducedMotion === false
348
+ ? true
349
+ : reducedMotion === true
350
+ ? false
351
+ : shouldAnimate && !prefersReducedMotionNow();
352
+ let palette = colors.map((c) => canvasColor(container, c));
353
+ let scene;
354
+ let stillOn = false;
355
+ const handle = createStage(canvas, container, {
356
+ frame: (_stage, dt) => {
357
+ if (!scene)
358
+ return false;
359
+ if (!motion) {
360
+ if (stillOn)
361
+ scene.draw(palette);
362
+ return false;
363
+ }
364
+ scene.step(dt * speed, activeRef.current);
365
+ scene.draw(palette);
366
+ return activeRef.current || scene.alive();
367
+ },
368
+ });
369
+ if (!handle)
47
370
  return;
48
- // Set canvas size
49
- let canvasWidth = 0;
50
- let canvasHeight = 0;
51
- const updateSize = () => {
52
- const rect = container.getBoundingClientRect();
53
- canvasWidth = rect.width;
54
- canvasHeight = rect.height;
55
- canvas.width = rect.width * 2; // 2x for retina
56
- canvas.height = rect.height * 2;
57
- canvas.style.width = `${rect.width}px`;
58
- canvas.style.height = `${rect.height}px`;
59
- ctx.scale(2, 2); // Scale for retina
371
+ handle.stage.dark = isDarkBackground(container);
372
+ scene =
373
+ type === "fireworks"
374
+ ? fireworksScene(handle.stage, count, palette.length)
375
+ : confettiScene(handle.stage, count, palette.length);
376
+ const run = {
377
+ scene,
378
+ handle,
379
+ motion,
380
+ showStill: (on, x, y) => {
381
+ stillOn = on;
382
+ if (on)
383
+ scene?.still(x, y);
384
+ else
385
+ scene?.clear();
386
+ handle.paint();
387
+ },
60
388
  };
61
- updateSize();
62
- window.addEventListener("resize", updateSize);
63
- // Parse colors - convert token names to CSS variables
64
- const parsedColors = colors.map((color) => {
65
- const computedColor = getComputedStyle(container).getPropertyValue(`--${color}`);
66
- return computedColor || color;
67
- });
68
- // Initialize confetti
69
- const initializeConfetti = () => {
70
- const particles = [];
71
- const shapes = ["rectangle", "circle", "triangle"];
72
- for (let i = 0; i < intensity; i++) {
73
- // Stagger particles more dramatically over a larger vertical range
74
- const stagger = (i / intensity) * canvasHeight * 2;
75
- particles.push({
76
- x: Math.random() * canvasWidth,
77
- y: -canvasHeight - Math.random() * canvasHeight - stagger,
78
- width: 8 + Math.random() * 8,
79
- height: 6 + Math.random() * 6,
80
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
81
- rotation: Math.random() * Math.PI * 2,
82
- rotationSpeed: (Math.random() - 0.5) * 0.2,
83
- velocityX: (Math.random() - 0.5) * 3,
84
- velocityY: (0.5 + Math.random() * 2.5) * speed,
85
- gravity: (0.12 + Math.random() * 0.06) * speed,
86
- opacity: 0.8 + Math.random() * 0.2,
87
- shape: shapes[Math.floor(Math.random() * shapes.length)],
88
- });
389
+ runRef.current = run;
390
+ if (activeRef.current) {
391
+ startedRef.current = true;
392
+ if (motion) {
393
+ scene.start();
394
+ handle.wake();
89
395
  }
90
- return particles;
91
- };
92
- // Create a new firework (explodes immediately at random or click position)
93
- const createFirework = (clickPos) => {
94
- const firework = {
95
- x: clickPos ? clickPos.x : Math.random() * canvasWidth,
96
- y: clickPos ? clickPos.y : canvasHeight * (0.2 + Math.random() * 0.4),
97
- targetY: 0, // Not used anymore
98
- velocityY: 0,
99
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
100
- exploded: true, // Start already exploded
101
- particles: [],
102
- };
103
- // Explode immediately
104
- explodeFirework(firework);
105
- return firework;
106
- };
107
- // Explode firework into particles
108
- const explodeFirework = (firework) => {
109
- const particleCount = 30 + Math.floor(Math.random() * 20);
110
- for (let i = 0; i < particleCount; i++) {
111
- const angle = (Math.PI * 2 * i) / particleCount;
112
- const velocity = 1 + Math.random() * 3;
113
- firework.particles.push({
114
- x: firework.x,
115
- y: firework.y,
116
- velocityX: Math.cos(angle) * velocity * speed,
117
- velocityY: Math.sin(angle) * velocity * speed,
118
- color: firework.color,
119
- opacity: 1,
120
- size: 1 + Math.random(),
121
- life: 0,
122
- maxLife: 60 + Math.random() * 40,
123
- });
396
+ else {
397
+ run.showStill(true);
124
398
  }
125
- firework.exploded = true;
126
- };
127
- // Initialize particles only if not already initialized
128
- if (particlesRef.current.length === 0 && type === "confetti") {
129
- particlesRef.current = initializeConfetti();
130
399
  }
131
- // Animation loop
132
- const animate = () => {
133
- ctx.clearRect(0, 0, canvasWidth, canvasHeight);
134
- // Check if we should still be emitting new particles
135
- const shouldEmit = trigger === "hover"
136
- ? isHoveredRef.current
137
- : trigger === "manual"
138
- ? // Read from the ref the manual-trigger effect keeps in step with
139
- // `active`: this loop's closure holds the `active` it started with.
140
- isEmittingRef.current
141
- : trigger === "click"
142
- ? clickPositionRef.current !== null
143
- : isEmittingRef.current;
144
- // Check duration limit
145
- if (duration && isEmittingRef.current && trigger !== "manual") {
146
- const elapsed = Date.now() - emitStartTimeRef.current;
147
- if (elapsed > duration) {
148
- isEmittingRef.current = false;
149
- }
150
- }
151
- if (type === "confetti") {
152
- // Update and draw confetti
153
- particlesRef.current.forEach((piece) => {
154
- // Update physics
155
- piece.velocityY += piece.gravity;
156
- piece.x += piece.velocityX;
157
- piece.y += piece.velocityY;
158
- piece.rotation += piece.rotationSpeed;
159
- // Add some air resistance
160
- piece.velocityX *= 0.99;
161
- // Only respawn if we're still emitting
162
- if (piece.y > canvasHeight + 50 && shouldEmit) {
163
- piece.y = -20 - Math.random() * canvasHeight * 0.5;
164
- piece.x = Math.random() * canvasWidth;
165
- piece.velocityX = (Math.random() - 0.5) * 3;
166
- piece.velocityY = (0.5 + Math.random() * 2.5) * speed;
167
- piece.gravity = (0.12 + Math.random() * 0.06) * speed;
168
- }
169
- // Only draw if still on screen
170
- if (piece.y < canvasHeight + 100) {
171
- // Draw confetti piece
172
- ctx.save();
173
- ctx.translate(piece.x, piece.y);
174
- ctx.rotate(piece.rotation);
175
- ctx.globalAlpha = piece.opacity;
176
- ctx.fillStyle = piece.color;
177
- if (piece.shape === "rectangle") {
178
- ctx.fillRect(-piece.width / 2, -piece.height / 2, piece.width, piece.height);
179
- }
180
- else if (piece.shape === "circle") {
181
- ctx.beginPath();
182
- ctx.arc(0, 0, piece.width / 2, 0, Math.PI * 2);
183
- ctx.fill();
184
- }
185
- else if (piece.shape === "triangle") {
186
- ctx.beginPath();
187
- ctx.moveTo(0, -piece.height / 2);
188
- ctx.lineTo(piece.width / 2, piece.height / 2);
189
- ctx.lineTo(-piece.width / 2, piece.height / 2);
190
- ctx.closePath();
191
- ctx.fill();
192
- }
193
- ctx.restore();
194
- }
195
- });
196
- }
197
- else if (type === "fireworks") {
198
- // Launch new fireworks
199
- if (trigger === "click" && clickPositionRef.current) {
200
- // Fire from click position
201
- particlesRef.current.push(createFirework(clickPositionRef.current));
202
- clickPositionRef.current = null;
203
- }
204
- else {
205
- fireworkTimerRef.current++;
206
- if (shouldEmit && fireworkTimerRef.current > 20 / speed) {
207
- // Launch new firework every ~20 frames
208
- fireworkTimerRef.current = 0;
209
- particlesRef.current.push(createFirework());
210
- }
211
- }
212
- // Update and draw fireworks (explosion particles only)
213
- particlesRef.current.forEach((firework) => {
214
- // Update and draw explosion particles
215
- firework.particles.forEach((particle) => {
216
- particle.life++;
217
- if (particle.life < particle.maxLife) {
218
- // Update position
219
- particle.x += particle.velocityX;
220
- particle.y += particle.velocityY;
221
- particle.velocityY += 0.1; // Gravity
222
- // Fade out
223
- particle.opacity = 1 - particle.life / particle.maxLife;
224
- // Draw particle
225
- ctx.globalAlpha = particle.opacity;
226
- ctx.fillStyle = particle.color;
227
- ctx.beginPath();
228
- ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
229
- ctx.fill();
230
- }
231
- });
232
- });
233
- // Clean up dead fireworks (only when not emitting)
234
- if (!shouldEmit) {
235
- particlesRef.current = particlesRef.current.filter((firework) => {
236
- // Keep if any particles are still alive
237
- return firework.particles.some((p) => p.life < p.maxLife);
238
- });
239
- }
240
- }
241
- ctx.globalAlpha = 1;
242
- animationRef.current = requestAnimationFrame(animate);
243
- };
244
- if (shouldAnimate) {
245
- animate();
400
+ else {
401
+ startedRef.current = false;
246
402
  }
403
+ const unwatch = watchTheme(() => {
404
+ palette = colors.map((c) => canvasColor(container, c));
405
+ handle.stage.dark = isDarkBackground(container);
406
+ if (!motion)
407
+ handle.paint();
408
+ });
247
409
  return () => {
248
- window.removeEventListener("resize", updateSize);
249
- if (animationRef.current) {
250
- cancelAnimationFrame(animationRef.current);
251
- }
410
+ unwatch();
411
+ handle.stop();
412
+ if (runRef.current === run)
413
+ runRef.current = null;
252
414
  };
253
- }, [type, colors, speed, intensity, duration, trigger, shouldAnimate]);
254
- const handleMouseEnter = () => {
255
- if (trigger === "hover" && !isHoveredRef.current) {
256
- isHoveredRef.current = true;
257
- isEmittingRef.current = true;
258
- emitStartTimeRef.current = Date.now();
259
- }
260
- };
261
- const handleMouseLeave = () => {
262
- if (trigger === "hover" && isHoveredRef.current) {
263
- isHoveredRef.current = false;
264
- }
265
- };
266
- const handleClick = (e) => {
267
- if (trigger === "click" && containerRef.current) {
268
- const rect = containerRef.current.getBoundingClientRect();
269
- const x = e.clientX - rect.left;
270
- const y = e.clientY - rect.top;
271
- if (type === "confetti") {
272
- // For confetti, add burst of particles from click position
273
- const shapes = ["rectangle", "circle", "triangle"];
274
- const canvas = canvasRef.current;
275
- if (!canvas)
276
- return;
277
- const parsedColors = colors.map((color) => {
278
- const computedColor = getComputedStyle(containerRef.current).getPropertyValue(`--${color}`);
279
- return computedColor || color;
280
- });
281
- for (let i = 0; i < intensity; i++) {
282
- const angle = (Math.PI * 2 * i) / intensity;
283
- const velocity = 2 + Math.random() * 3;
284
- particlesRef.current.push({
285
- x,
286
- y,
287
- width: 8 + Math.random() * 8,
288
- height: 6 + Math.random() * 6,
289
- color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
290
- rotation: Math.random() * Math.PI * 2,
291
- rotationSpeed: (Math.random() - 0.5) * 0.2,
292
- velocityX: Math.cos(angle) * velocity,
293
- velocityY: Math.sin(angle) * velocity - 2, // Slight upward bias
294
- gravity: (0.12 + Math.random() * 0.06) * speed,
295
- opacity: 0.8 + Math.random() * 0.2,
296
- shape: shapes[Math.floor(Math.random() * shapes.length)],
297
- });
298
- }
415
+ }, [type, colorsKey, speed, count, reducedMotion, shouldAnimate]);
416
+ // `active` turning on starts a celebration; turning off lets it settle.
417
+ useEffect(() => {
418
+ const run = runRef.current;
419
+ if (!run)
420
+ return;
421
+ if (active && !startedRef.current) {
422
+ startedRef.current = true;
423
+ if (run.motion) {
424
+ run.scene.start();
425
+ run.handle.wake();
299
426
  }
300
427
  else {
301
- // For fireworks, store click position
302
- clickPositionRef.current = { x, y };
428
+ run.showStill(true);
303
429
  }
304
430
  }
431
+ else if (!active && startedRef.current) {
432
+ startedRef.current = false;
433
+ if (!run.motion)
434
+ run.showStill(false);
435
+ }
436
+ }, [active]);
437
+ // `duration` ends it.
438
+ useEffect(() => {
439
+ if (!active || !(duration > 0) || !Number.isFinite(duration))
440
+ return;
441
+ const timer = setTimeout(() => setActive(false), duration);
442
+ return () => clearTimeout(timer);
443
+ }, [active, duration, setActive]);
444
+ const hoverIsTap = trigger === "hover" && cannotHover();
445
+ const handleMouseEnter = (event) => {
446
+ onMouseEnter?.(event);
447
+ if (trigger === "hover" && !hoverIsTap)
448
+ setActive(true);
449
+ };
450
+ const handleMouseLeave = (event) => {
451
+ onMouseLeave?.(event);
452
+ if (trigger === "hover" && !hoverIsTap)
453
+ setActive(false);
454
+ };
455
+ const handleClick = (event) => {
456
+ onClick?.(event);
457
+ if (hoverIsTap) {
458
+ setActive(true);
459
+ return;
460
+ }
461
+ if (trigger !== "click" || !containerRef.current)
462
+ return;
463
+ const run = runRef.current;
464
+ if (!run)
465
+ return;
466
+ const rect = containerRef.current.getBoundingClientRect();
467
+ const x = event.clientX - rect.left;
468
+ const y = event.clientY - rect.top;
469
+ if (run.motion) {
470
+ run.scene.burst(x, y);
471
+ run.handle.wake();
472
+ }
473
+ else {
474
+ run.showStill(true, x, y);
475
+ setTimeout(() => {
476
+ if (runRef.current === run && !activeRef.current)
477
+ run.showStill(false);
478
+ }, 1200);
479
+ }
305
480
  };
306
- return (_jsxs(Flex, { ref: containerRef, fill: true, overflow: "hidden", onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onClick: handleClick, ...rest, style: {
307
- cursor: trigger === "click" ? "pointer" : undefined,
308
- ...style,
309
- }, children: [_jsx("canvas", { ref: canvasRef, "aria-hidden": "true", style: {
481
+ 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: {
310
482
  position: "absolute",
311
483
  top: 0,
312
484
  left: 0,