@once-ui-system/fx 0.0.0-stage → 3.0.0-beta.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 (55) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +16 -2
  3. package/dist/BlobFx.d.ts +10 -0
  4. package/dist/BlobFx.js +86 -0
  5. package/dist/CelebrationFx.d.ts +21 -0
  6. package/dist/CelebrationFx.js +319 -0
  7. package/dist/CountFx.d.ts +19 -0
  8. package/dist/CountFx.js +226 -0
  9. package/dist/CountdownFx.d.ts +13 -0
  10. package/dist/CountdownFx.js +65 -0
  11. package/dist/Effect.d.ts +52 -0
  12. package/dist/Effect.js +33 -0
  13. package/dist/FlipFx.d.ts +20 -0
  14. package/dist/FlipFx.js +71 -0
  15. package/dist/GlitchFx.d.ts +19 -0
  16. package/dist/GlitchFx.js +41 -0
  17. package/dist/GlitchFx.module.css +78 -0
  18. package/dist/HoloFx.d.ts +34 -0
  19. package/dist/HoloFx.js +99 -0
  20. package/dist/HoloFx.module.css +29 -0
  21. package/dist/LetterFx.d.ts +24 -0
  22. package/dist/LetterFx.js +83 -0
  23. package/dist/MatrixFx.d.ts +32 -0
  24. package/dist/MatrixFx.js +886 -0
  25. package/dist/ParticleFx.d.ts +26 -0
  26. package/dist/ParticleFx.js +154 -0
  27. package/dist/RevealFx.d.ts +27 -0
  28. package/dist/RevealFx.js +65 -0
  29. package/dist/RevealFx.module.css +25 -0
  30. package/dist/ShineFx.d.ts +17 -0
  31. package/dist/ShineFx.js +17 -0
  32. package/dist/ShineFx.module.css +37 -0
  33. package/dist/TiltFx.d.ts +12 -0
  34. package/dist/TiltFx.js +79 -0
  35. package/dist/TiltFx.module.css +11 -0
  36. package/dist/TypeFx.d.ts +41 -0
  37. package/dist/TypeFx.js +102 -0
  38. package/dist/WeatherFx.d.ts +22 -0
  39. package/dist/WeatherFx.js +869 -0
  40. package/dist/index.d.ts +16 -0
  41. package/dist/index.js +19 -0
  42. package/dist/internal/FadingLetters.d.ts +8 -0
  43. package/dist/internal/FadingLetters.js +21 -0
  44. package/dist/internal/FadingLetters.module.css +224 -0
  45. package/dist/internal/cssColor.d.ts +4 -0
  46. package/dist/internal/cssColor.js +70 -0
  47. package/dist/internal/pointer.d.ts +9 -0
  48. package/dist/internal/pointer.js +11 -0
  49. package/dist/internal/reducedMotion.d.ts +7 -0
  50. package/dist/internal/reducedMotion.js +11 -0
  51. package/dist/internal/speed.d.ts +13 -0
  52. package/dist/internal/speed.js +15 -0
  53. package/dist/internal/translate.d.ts +13 -0
  54. package/dist/internal/translate.js +81 -0
  55. package/package.json +78 -4
@@ -0,0 +1,886 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Flex, useReducedMotion } from "@once-ui-system/core";
4
+ import { useEffect, useRef } from "react";
5
+ import { speedFactor } from "./internal/speed.js";
6
+ const MatrixFx = ({ ref: forwardedRef, speed: speedProp, colors = ["brand-solid-medium"], size = 3, spacing = 3, revealFrom = "center", trigger = "instant", active = false, flicker = false, bulge, fps = 60, reducedMotion = "auto", children, ...rest }) => {
7
+ const speed = speedFactor(speedProp);
8
+ const { shouldAnimate } = useReducedMotion(reducedMotion);
9
+ const containerRef = useRef(null);
10
+ const canvasRef = useRef(null);
11
+ const animationRef = useRef(undefined);
12
+ const revealStartTimeRef = useRef(Date.now());
13
+ const hideStartTimeRef = useRef(Date.now());
14
+ const maxRevealProgressRef = useRef(0);
15
+ const hideStartProgressRef = useRef(0);
16
+ const isHoveredRef = useRef(false);
17
+ const mountAnimationCompleteRef = useRef(false);
18
+ const bulgeStartTimeRef = useRef(Date.now());
19
+ const dotsRef = useRef([]);
20
+ const lastFrameTimeRef = useRef(0);
21
+ const isStaticRef = useRef(false);
22
+ const isVisibleRef = useRef(true);
23
+ const animateFnRef = useRef(null);
24
+ useEffect(() => {
25
+ if (forwardedRef) {
26
+ if ("current" in forwardedRef) {
27
+ forwardedRef.current = containerRef.current;
28
+ }
29
+ else if (typeof forwardedRef === "function") {
30
+ forwardedRef(containerRef.current);
31
+ }
32
+ }
33
+ }, [forwardedRef]);
34
+ // Viewport visibility detection
35
+ useEffect(() => {
36
+ const container = containerRef.current;
37
+ if (!container)
38
+ return;
39
+ const observer = new IntersectionObserver((entries) => {
40
+ entries.forEach((entry) => {
41
+ isVisibleRef.current = entry.isIntersecting;
42
+ });
43
+ }, {
44
+ // Start animating when 10% visible for smooth transitions
45
+ threshold: 0.1,
46
+ // Add margin to start rendering slightly before entering viewport
47
+ rootMargin: "50px",
48
+ });
49
+ observer.observe(container);
50
+ return () => {
51
+ observer.disconnect();
52
+ };
53
+ }, []);
54
+ useEffect(() => {
55
+ const canvas = canvasRef.current;
56
+ const container = containerRef.current;
57
+ if (!canvas || !container)
58
+ return;
59
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
60
+ if (!ctx)
61
+ return;
62
+ // Set canvas size — skip until the container has layout (0×0 crashes getImageData)
63
+ let canvasWidth = 0;
64
+ let canvasHeight = 0;
65
+ let initialized = false;
66
+ let disposed = false;
67
+ // Returns whether the canvas now has a size. Writing canvas.width or
68
+ // height clears the bitmap even when the value is the same, so an
69
+ // unchanged box is left alone: a static grid (reduced motion, or no
70
+ // flicker) is drawn once and nothing would paint it back.
71
+ const applySize = () => {
72
+ const rect = container.getBoundingClientRect();
73
+ if (rect.width <= 0 || rect.height <= 0) {
74
+ return false;
75
+ }
76
+ if (rect.width === canvasWidth && rect.height === canvasHeight) {
77
+ return true;
78
+ }
79
+ canvasWidth = rect.width;
80
+ canvasHeight = rect.height;
81
+ canvas.width = Math.floor(rect.width * 2);
82
+ canvas.height = Math.floor(rect.height * 2);
83
+ canvas.style.width = `${rect.width}px`;
84
+ canvas.style.height = `${rect.height}px`;
85
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
86
+ ctx.scale(2, 2);
87
+ return true;
88
+ };
89
+ // A real resize cleared the canvas and left the grid, its center and the
90
+ // cached static frame sized for the old box, and a stopped loop would
91
+ // never redraw it. Rebuild for the new size and restart the loop.
92
+ const handleResize = () => {
93
+ if (!initialized) {
94
+ setup();
95
+ return;
96
+ }
97
+ const prevW = canvasWidth;
98
+ const prevH = canvasHeight;
99
+ if (!applySize())
100
+ return;
101
+ if (prevW === canvasWidth && prevH === canvasHeight)
102
+ return;
103
+ if (animationRef.current) {
104
+ cancelAnimationFrame(animationRef.current);
105
+ animationRef.current = undefined;
106
+ }
107
+ dotsRef.current = [];
108
+ isStaticRef.current = false;
109
+ initialized = false;
110
+ setup();
111
+ };
112
+ window.addEventListener("resize", handleResize);
113
+ const setup = () => {
114
+ if (disposed || initialized)
115
+ return;
116
+ if (!applySize())
117
+ return;
118
+ initialized = true;
119
+ // Parse colors - convert token names to CSS variables
120
+ const parsedColors = colors.map((color) => {
121
+ const computedColor = getComputedStyle(container).getPropertyValue(`--${color}`);
122
+ return computedColor || color;
123
+ });
124
+ // Create dot grid with padding to prevent edge gaps during displacement
125
+ const totalSize = size + spacing;
126
+ const maxDisplacement = (bulge?.intensity ?? 10) * 2;
127
+ const paddedWidth = canvasWidth + maxDisplacement * 2;
128
+ const paddedHeight = canvasHeight + maxDisplacement * 2;
129
+ const cols = Math.ceil(paddedWidth / totalSize);
130
+ const rows = Math.ceil(paddedHeight / totalSize);
131
+ let dots = dotsRef.current;
132
+ let maxDistance = 0;
133
+ if (dots.length === 0 ||
134
+ dots[0]?.gridSize !== totalSize ||
135
+ dots[0]?.canvasW !== canvasWidth ||
136
+ dots[0]?.canvasH !== canvasHeight) {
137
+ dots = [];
138
+ for (let row = 0; row < rows; row++) {
139
+ for (let col = 0; col < cols; col++) {
140
+ const x = col * totalSize + size / 2 - maxDisplacement;
141
+ const y = row * totalSize + size / 2 - maxDisplacement;
142
+ let distanceFromOrigin = 0;
143
+ const centerX = canvasWidth / 2;
144
+ const centerY = canvasHeight / 2;
145
+ switch (revealFrom) {
146
+ case "center": {
147
+ const dx = x - centerX;
148
+ const dy = y - centerY;
149
+ distanceFromOrigin = Math.sqrt(dx * dx + dy * dy);
150
+ break;
151
+ }
152
+ case "top":
153
+ distanceFromOrigin = y;
154
+ break;
155
+ case "bottom":
156
+ distanceFromOrigin = canvasHeight - y;
157
+ break;
158
+ case "left":
159
+ distanceFromOrigin = x;
160
+ break;
161
+ case "right":
162
+ distanceFromOrigin = canvasWidth - x;
163
+ break;
164
+ }
165
+ dots.push({
166
+ x,
167
+ y,
168
+ gridX: col,
169
+ gridY: row,
170
+ color: parsedColors[Math.floor(Math.random() * parsedColors.length)],
171
+ baseOpacity: 0.3 + Math.random() * 0.7,
172
+ distanceFromOrigin,
173
+ randomOffset: Math.random() * 0.3,
174
+ flickerPhase: Math.random() * Math.PI * 2,
175
+ flickerSpeed: 0.8 + Math.random() * 0.4,
176
+ gridSize: totalSize,
177
+ canvasW: canvasWidth,
178
+ canvasH: canvasHeight,
179
+ });
180
+ }
181
+ }
182
+ maxDistance = dots.length > 0 ? Math.max(...dots.map((d) => d.distanceFromOrigin)) : 0;
183
+ dotsRef.current = dots;
184
+ }
185
+ else {
186
+ dots.forEach((dot) => {
187
+ dot.color = parsedColors[Math.floor(Math.random() * parsedColors.length)];
188
+ });
189
+ maxDistance = dots.length > 0 ? Math.max(...dots.map((d) => d.distanceFromOrigin)) : 0;
190
+ }
191
+ const startTime = Date.now();
192
+ const frameInterval = 1000 / fps;
193
+ // Under reduced motion nothing keeps moving: no flicker, no bulge wave.
194
+ // Without this, either one kept the frame loop running indefinitely.
195
+ const bulgeEnabled = !!bulge && shouldAnimate;
196
+ const flickering = flicker && shouldAnimate;
197
+ const bulgeType = bulge?.type ?? "ripple";
198
+ // In seconds below, like the elapsed time it is compared with.
199
+ const bulgeDuration = (bulge?.duration ?? 3000) / 1000;
200
+ const bulgeIntensity = bulge?.intensity ?? 10;
201
+ const bulgeRepeat = bulge?.repeat ?? true;
202
+ const bulgeDelay = bulge?.delay ?? 0;
203
+ const centerX = canvasWidth / 2;
204
+ const centerY = canvasHeight / 2;
205
+ const maxRadius = Math.sqrt(centerX * centerX + centerY * centerY);
206
+ let cachedImageData = null;
207
+ const cacheStaticFrame = () => {
208
+ if (canvas.width <= 0 || canvas.height <= 0)
209
+ return;
210
+ try {
211
+ cachedImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
212
+ }
213
+ catch {
214
+ cachedImageData = null;
215
+ }
216
+ };
217
+ // When reduced motion is active, force static rendering after first frame
218
+ if (!shouldAnimate) {
219
+ isStaticRef.current = true;
220
+ mountAnimationCompleteRef.current = true;
221
+ }
222
+ const animate = (currentTime = 0) => {
223
+ if (canvasWidth <= 0 || canvasHeight <= 0) {
224
+ animationRef.current = requestAnimationFrame(animate);
225
+ return;
226
+ }
227
+ // Skip rendering if not visible in viewport
228
+ if (!isVisibleRef.current) {
229
+ animationRef.current = requestAnimationFrame(animate);
230
+ return;
231
+ }
232
+ // FPS throttling
233
+ if (currentTime - lastFrameTimeRef.current < frameInterval) {
234
+ animationRef.current = requestAnimationFrame(animate);
235
+ return;
236
+ }
237
+ lastFrameTimeRef.current = currentTime;
238
+ // If static and we have cached image, just render that and stop animating
239
+ if (isStaticRef.current && cachedImageData) {
240
+ ctx.putImageData(cachedImageData, 0, 0);
241
+ // Don't request another frame - animation is complete. Clear the
242
+ // ref so the loop can be restarted.
243
+ animationRef.current = undefined;
244
+ return;
245
+ }
246
+ ctx.clearRect(0, 0, canvasWidth, canvasHeight);
247
+ const time = (Date.now() - startTime) / 1000; // Time in seconds
248
+ // Calculate circular wave radius (travels from center to edge)
249
+ let waveProgress = 0;
250
+ let showBulge = false;
251
+ let bulgeFadeOut = 1; // Multiplier for fading out bulge effect (1 = full effect, 0 = no effect)
252
+ if (bulgeEnabled) {
253
+ const bulgeElapsed = (Date.now() - bulgeStartTimeRef.current) / 1000;
254
+ const delaySeconds = bulgeDelay / 1000;
255
+ const totalCycleDuration = bulgeDuration + delaySeconds;
256
+ const adjustedTime = bulgeElapsed - delaySeconds;
257
+ const fadeStartPercent = 0.6; // Start fading at 60% of wave duration
258
+ if (adjustedTime >= 0) {
259
+ showBulge = true;
260
+ if (bulgeRepeat) {
261
+ // Continuous repeating wave
262
+ const cycleTime = adjustedTime % totalCycleDuration;
263
+ waveProgress = cycleTime < bulgeDuration ? cycleTime / bulgeDuration : 0;
264
+ showBulge = cycleTime < bulgeDuration; // Only show during active wave, not delay
265
+ }
266
+ else {
267
+ // Single wave with opacity fade during last 40%
268
+ if (adjustedTime <= bulgeDuration) {
269
+ waveProgress = adjustedTime / bulgeDuration;
270
+ // Start fading opacity at 60% of duration
271
+ if (waveProgress >= fadeStartPercent) {
272
+ const fadeProgress = (waveProgress - fadeStartPercent) / (1 - fadeStartPercent);
273
+ bulgeFadeOut = 1 - fadeProgress; // Fade from 1 to 0
274
+ }
275
+ }
276
+ else {
277
+ waveProgress = 0;
278
+ showBulge = false;
279
+ }
280
+ }
281
+ }
282
+ }
283
+ const waveRadius = waveProgress * maxRadius * 1.5; // Travel beyond edges for smooth cycle
284
+ // For instant trigger, show all dots immediately at full opacity
285
+ if (trigger === "instant") {
286
+ // Check if we're in a static state (no flicker, no active bulge)
287
+ const isCurrentlyStatic = !flickering && (!bulgeEnabled || !showBulge);
288
+ if (isCurrentlyStatic && isStaticRef.current && cachedImageData) {
289
+ // Use cached render
290
+ ctx.putImageData(cachedImageData, 0, 0);
291
+ }
292
+ else {
293
+ // Render dots
294
+ dots.forEach((dot) => {
295
+ ctx.fillStyle = dot.color;
296
+ let opacity = dot.baseOpacity;
297
+ // Apply flicker effect if enabled
298
+ if (flickering) {
299
+ const flickerValue = Math.sin(time * dot.flickerSpeed * 3 + dot.flickerPhase);
300
+ const flickerMultiplier = 0.6 + flickerValue * 0.4; // Oscillate between 0.6 and 1.0
301
+ opacity *= flickerMultiplier;
302
+ }
303
+ // Calculate bulge displacement
304
+ let offsetX = 0;
305
+ let offsetY = 0;
306
+ let sizeMultiplier = 1;
307
+ let bulgeOpacity = 1;
308
+ if (bulgeEnabled && showBulge) {
309
+ if (bulgeType === "ripple") {
310
+ // Ripple: circular wave from center
311
+ const dx = dot.x - centerX;
312
+ const dy = dot.y - centerY;
313
+ const distanceFromCenter = Math.sqrt(dx * dx + dy * dy);
314
+ const distanceToWave = Math.abs(distanceFromCenter - waveRadius);
315
+ const waveWidth = maxRadius * 0.15;
316
+ const distanceNorm = distanceToWave / waveWidth;
317
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 4);
318
+ const angle = Math.atan2(dy, dx);
319
+ const displacementAmount = waveFactor * bulgeIntensity * bulgeFadeOut;
320
+ offsetX = Math.cos(angle) * displacementAmount;
321
+ offsetY = Math.sin(angle) * displacementAmount;
322
+ sizeMultiplier = 1 + waveFactor * 0.8 * bulgeFadeOut;
323
+ const waveOpacity = 0.3 + waveFactor * 0.7;
324
+ bulgeOpacity = 1 + (waveOpacity - 1) * bulgeFadeOut;
325
+ }
326
+ else if (bulgeType === "wave") {
327
+ // Wave: Organic S-curve from bottom-left to top-right with rotation
328
+ const diagonalLength = Math.sqrt(canvasWidth * canvasWidth + canvasHeight * canvasHeight);
329
+ // Start wave off-screen before bottom-left, end off-screen after top-right
330
+ const wavePosOnDiagonal = waveProgress * diagonalLength * 1.4 - diagonalLength * 0.2;
331
+ // Calculate distance along the diagonal (from bottom-left to top-right)
332
+ const normalizedX = dot.x / canvasWidth;
333
+ const normalizedY = 1 - dot.y / canvasHeight;
334
+ const dotDiagonalPos = ((normalizedX + normalizedY) / 2) * diagonalLength;
335
+ // Distance from wave front
336
+ const distanceToWaveFront = dotDiagonalPos - wavePosOnDiagonal;
337
+ const waveWidth = diagonalLength * 0.25;
338
+ const distanceNorm = distanceToWaveFront / waveWidth;
339
+ // Smooth wave factor with wider influence
340
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 2.5);
341
+ // Create rotating S-curve with multiple frequency components
342
+ const perpendicularOffset = normalizedY - normalizedX;
343
+ // Primary S-curve that rotates over time
344
+ const rotationPhase = waveProgress * Math.PI * 3; // Rotates 1.5 times during animation
345
+ const primaryFreq = 3; // Number of S-curves along the wave
346
+ const sCurvePrimary = Math.sin(perpendicularOffset * Math.PI * primaryFreq + rotationPhase);
347
+ // Secondary curve for complexity (higher frequency, lower amplitude)
348
+ const secondaryFreq = 7;
349
+ const sCurveSecondary = Math.sin(perpendicularOffset * Math.PI * secondaryFreq - rotationPhase * 1.5) *
350
+ 0.4;
351
+ // Combine curves for organic motion
352
+ const sCurveFactor = sCurvePrimary + sCurveSecondary;
353
+ // Wave straightens at the edges (distanceNorm affects curve strength)
354
+ const curveStrength = 1 - Math.abs(distanceNorm) * 0.5;
355
+ const modulatedCurve = sCurveFactor * curveStrength;
356
+ // Apply displacement
357
+ const baseDisplacement = waveFactor * bulgeIntensity * bulgeFadeOut;
358
+ const diagonalAngle = Math.PI / 4;
359
+ // Perpendicular displacement creates the S-curve
360
+ const perpAngle = diagonalAngle + Math.PI / 2;
361
+ offsetX =
362
+ Math.cos(diagonalAngle) * baseDisplacement +
363
+ Math.cos(perpAngle) * modulatedCurve * baseDisplacement * 0.8;
364
+ offsetY =
365
+ -Math.sin(diagonalAngle) * baseDisplacement -
366
+ Math.sin(perpAngle) * modulatedCurve * baseDisplacement * 0.8;
367
+ sizeMultiplier = 1 + waveFactor * 0.5 * bulgeFadeOut;
368
+ const waveOpacity = 0.4 + waveFactor * 0.6;
369
+ bulgeOpacity = 1 + (waveOpacity - 1) * bulgeFadeOut;
370
+ }
371
+ }
372
+ ctx.globalAlpha = opacity * bulgeOpacity;
373
+ const adjustedSize = size * sizeMultiplier;
374
+ const sizeOffset = (adjustedSize - size) / 2;
375
+ ctx.fillRect(dot.x + offsetX - sizeOffset, dot.y + offsetY - sizeOffset, adjustedSize, adjustedSize);
376
+ });
377
+ // Cache if now static
378
+ if (isCurrentlyStatic) {
379
+ cacheStaticFrame();
380
+ isStaticRef.current = true;
381
+ }
382
+ }
383
+ ctx.globalAlpha = 1;
384
+ // Only continue animating if there's something dynamic (flicker or bulge)
385
+ if (!isCurrentlyStatic) {
386
+ animationRef.current = requestAnimationFrame(animate);
387
+ }
388
+ else {
389
+ // Clear the ref so the animation can be restarted
390
+ animationRef.current = undefined;
391
+ }
392
+ return;
393
+ }
394
+ // For mount trigger - progressive reveal on load, then static
395
+ if (trigger === "mount") {
396
+ if (!mountAnimationCompleteRef.current) {
397
+ // Revealing animation with explosive easing
398
+ const now = Date.now();
399
+ const elapsed = (now - revealStartTimeRef.current) / 1000;
400
+ // Cubic easing: starts very slow, then explodes
401
+ const revealProgress = elapsed ** 3 * speed * 3;
402
+ // Check if animation is complete (max offset is ~1.3)
403
+ if (revealProgress >= 2.0) {
404
+ mountAnimationCompleteRef.current = true;
405
+ }
406
+ dots.forEach((dot) => {
407
+ const normalizedDistance = dot.distanceFromOrigin / maxDistance;
408
+ const introOffset = normalizedDistance * 0.8 + dot.randomOffset * 0.5;
409
+ let opacity = 0;
410
+ if (revealProgress > introOffset) {
411
+ const fadeIn = (revealProgress - introOffset) * 8;
412
+ opacity = Math.min(1, fadeIn * fadeIn) * dot.baseOpacity;
413
+ // Apply flicker effect if enabled
414
+ if (flickering) {
415
+ const flickerValue = Math.sin(time * dot.flickerSpeed * 3 + dot.flickerPhase);
416
+ const flickerMultiplier = 0.6 + flickerValue * 0.4;
417
+ opacity *= flickerMultiplier;
418
+ }
419
+ }
420
+ if (opacity > 0) {
421
+ // Calculate bulge displacement
422
+ let offsetX = 0;
423
+ let offsetY = 0;
424
+ let sizeMultiplier = 1;
425
+ let bulgeOpacity = 1;
426
+ if (bulgeEnabled) {
427
+ if (bulgeType === "ripple") {
428
+ const dx = dot.x - centerX;
429
+ const dy = dot.y - centerY;
430
+ const distanceFromCenter = Math.sqrt(dx * dx + dy * dy);
431
+ const distanceToWave = Math.abs(distanceFromCenter - waveRadius);
432
+ const waveWidth = maxRadius * 0.15;
433
+ const distanceNorm = distanceToWave / waveWidth;
434
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 4);
435
+ const angle = Math.atan2(dy, dx);
436
+ const displacementAmount = waveFactor * bulgeIntensity;
437
+ offsetX = Math.cos(angle) * displacementAmount;
438
+ offsetY = Math.sin(angle) * displacementAmount;
439
+ sizeMultiplier = 1 + waveFactor * 0.8;
440
+ bulgeOpacity = 0.3 + waveFactor * 0.7;
441
+ }
442
+ else if (bulgeType === "wave") {
443
+ const diagonalLength = Math.sqrt(canvasWidth * canvasWidth + canvasHeight * canvasHeight);
444
+ const wavePosOnDiagonal = waveProgress * diagonalLength * 1.2;
445
+ const normalizedX = dot.x / canvasWidth;
446
+ const normalizedY = 1 - dot.y / canvasHeight;
447
+ const dotDiagonalPos = ((normalizedX + normalizedY) / 2) * diagonalLength;
448
+ const distanceToWaveFront = dotDiagonalPos - wavePosOnDiagonal;
449
+ const waveWidth = diagonalLength * 0.2;
450
+ const distanceNorm = Math.abs(distanceToWaveFront) / waveWidth;
451
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 3);
452
+ const perpendicularOffset = normalizedY - normalizedX;
453
+ const sCurvePhase = perpendicularOffset * Math.PI * 2;
454
+ const sCurveFactor = Math.sin(sCurvePhase + waveProgress * Math.PI * 2);
455
+ const baseDisplacement = waveFactor * bulgeIntensity;
456
+ const diagonalAngle = Math.PI / 4;
457
+ offsetX =
458
+ Math.cos(diagonalAngle) * baseDisplacement +
459
+ sCurveFactor * baseDisplacement * 0.5;
460
+ offsetY =
461
+ -Math.sin(diagonalAngle) * baseDisplacement +
462
+ sCurveFactor * baseDisplacement * 0.5;
463
+ sizeMultiplier = 1 + waveFactor * 0.6;
464
+ bulgeOpacity = 0.4 + waveFactor * 0.6;
465
+ }
466
+ }
467
+ ctx.fillStyle = dot.color;
468
+ ctx.globalAlpha = opacity * bulgeOpacity;
469
+ const adjustedSize = size * sizeMultiplier;
470
+ const sizeOffset = (adjustedSize - size) / 2;
471
+ ctx.fillRect(dot.x + offsetX - sizeOffset, dot.y + offsetY - sizeOffset, adjustedSize, adjustedSize);
472
+ }
473
+ });
474
+ }
475
+ else {
476
+ // Animation complete - show all dots with optional flicker
477
+ const isCurrentlyStatic = !flickering && (!bulgeEnabled || !showBulge);
478
+ if (isCurrentlyStatic && isStaticRef.current && cachedImageData) {
479
+ // Use cached render for completed static state
480
+ ctx.putImageData(cachedImageData, 0, 0);
481
+ }
482
+ else {
483
+ dots.forEach((dot) => {
484
+ ctx.fillStyle = dot.color;
485
+ let opacity = dot.baseOpacity;
486
+ if (flickering) {
487
+ const flickerValue = Math.sin(time * dot.flickerSpeed * 3 + dot.flickerPhase);
488
+ const flickerMultiplier = 0.6 + flickerValue * 0.4;
489
+ opacity *= flickerMultiplier;
490
+ }
491
+ // Calculate bulge displacement
492
+ let offsetX = 0;
493
+ let offsetY = 0;
494
+ let sizeMultiplier = 1;
495
+ let bulgeOpacity = 1;
496
+ if (bulgeEnabled) {
497
+ if (bulgeType === "ripple") {
498
+ const dx = dot.x - centerX;
499
+ const dy = dot.y - centerY;
500
+ const distanceFromCenter = Math.sqrt(dx * dx + dy * dy);
501
+ const distanceToWave = Math.abs(distanceFromCenter - waveRadius);
502
+ const waveWidth = maxRadius * 0.15;
503
+ const distanceNorm = distanceToWave / waveWidth;
504
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 4);
505
+ const angle = Math.atan2(dy, dx);
506
+ const displacementAmount = waveFactor * bulgeIntensity;
507
+ offsetX = Math.cos(angle) * displacementAmount;
508
+ offsetY = Math.sin(angle) * displacementAmount;
509
+ sizeMultiplier = 1 + waveFactor * 0.8;
510
+ bulgeOpacity = 0.3 + waveFactor * 0.7;
511
+ }
512
+ else if (bulgeType === "wave") {
513
+ const diagonalLength = Math.sqrt(canvasWidth * canvasWidth + canvasHeight * canvasHeight);
514
+ const wavePosOnDiagonal = waveProgress * diagonalLength * 1.2;
515
+ const normalizedX = dot.x / canvasWidth;
516
+ const normalizedY = 1 - dot.y / canvasHeight;
517
+ const dotDiagonalPos = ((normalizedX + normalizedY) / 2) * diagonalLength;
518
+ const distanceToWaveFront = dotDiagonalPos - wavePosOnDiagonal;
519
+ const waveWidth = diagonalLength * 0.2;
520
+ const distanceNorm = Math.abs(distanceToWaveFront) / waveWidth;
521
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 3);
522
+ const perpendicularOffset = normalizedY - normalizedX;
523
+ const sCurvePhase = perpendicularOffset * Math.PI * 2;
524
+ const sCurveFactor = Math.sin(sCurvePhase + waveProgress * Math.PI * 2);
525
+ const baseDisplacement = waveFactor * bulgeIntensity;
526
+ const diagonalAngle = Math.PI / 4;
527
+ offsetX =
528
+ Math.cos(diagonalAngle) * baseDisplacement +
529
+ sCurveFactor * baseDisplacement * 0.5;
530
+ offsetY =
531
+ -Math.sin(diagonalAngle) * baseDisplacement +
532
+ sCurveFactor * baseDisplacement * 0.5;
533
+ sizeMultiplier = 1 + waveFactor * 0.6;
534
+ bulgeOpacity = 0.4 + waveFactor * 0.6;
535
+ }
536
+ }
537
+ ctx.globalAlpha = opacity * bulgeOpacity;
538
+ const adjustedSize = size * sizeMultiplier;
539
+ const sizeOffset = (adjustedSize - size) / 2;
540
+ ctx.fillRect(dot.x + offsetX - sizeOffset, dot.y + offsetY - sizeOffset, adjustedSize, adjustedSize);
541
+ });
542
+ // Cache if now static
543
+ if (isCurrentlyStatic) {
544
+ cacheStaticFrame();
545
+ isStaticRef.current = true;
546
+ }
547
+ }
548
+ }
549
+ ctx.globalAlpha = 1;
550
+ // Only continue animating if mount animation is incomplete or there's something dynamic
551
+ const isCurrentlyStatic = mountAnimationCompleteRef.current && !flickering && (!bulgeEnabled || !showBulge);
552
+ if (!isCurrentlyStatic) {
553
+ animationRef.current = requestAnimationFrame(animate);
554
+ }
555
+ else {
556
+ // Clear the ref so the animation can be restarted
557
+ animationRef.current = undefined;
558
+ }
559
+ return;
560
+ }
561
+ // For hover, click, and manual triggers with animation
562
+ if (trigger === "hover" || trigger === "click" || trigger === "manual") {
563
+ if (isHoveredRef.current) {
564
+ // Revealing animation with explosive easing
565
+ const now = Date.now();
566
+ const elapsed = (now - revealStartTimeRef.current) / 1000;
567
+ // Cubic easing: starts very slow, then explodes. Under reduced
568
+ // motion the grid shows in full at once.
569
+ const revealProgress = shouldAnimate ? elapsed ** 3 * speed * 3 : 2.0;
570
+ // Cap progress to prevent infinite growth (max offset is ~1.3)
571
+ const cappedProgress = Math.min(revealProgress, 2.0);
572
+ // Track maximum progress for reverse animation
573
+ maxRevealProgressRef.current = cappedProgress;
574
+ dots.forEach((dot) => {
575
+ const normalizedDistance = dot.distanceFromOrigin / maxDistance;
576
+ const introOffset = normalizedDistance * 0.8 + dot.randomOffset * 0.5; // Much lower threshold
577
+ let opacity = 0;
578
+ if (cappedProgress > introOffset) {
579
+ // Explosive opacity increase
580
+ const fadeIn = (cappedProgress - introOffset) * 8; // Faster fade-in
581
+ opacity = Math.min(1, fadeIn * fadeIn) * dot.baseOpacity;
582
+ // Apply flicker effect if enabled
583
+ if (flickering) {
584
+ const flickerValue = Math.sin(time * dot.flickerSpeed * 3 + dot.flickerPhase);
585
+ const flickerMultiplier = 0.6 + flickerValue * 0.4; // Oscillate between 0.6 and 1.0
586
+ opacity *= flickerMultiplier;
587
+ }
588
+ }
589
+ if (opacity > 0) {
590
+ // Calculate bulge displacement
591
+ let offsetX = 0;
592
+ let offsetY = 0;
593
+ let sizeMultiplier = 1;
594
+ let bulgeOpacity = 1;
595
+ if (bulgeEnabled) {
596
+ if (bulgeType === "ripple") {
597
+ const dx = dot.x - centerX;
598
+ const dy = dot.y - centerY;
599
+ const distanceFromCenter = Math.sqrt(dx * dx + dy * dy);
600
+ const distanceToWave = Math.abs(distanceFromCenter - waveRadius);
601
+ const waveWidth = maxRadius * 0.15;
602
+ const distanceNorm = distanceToWave / waveWidth;
603
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 4);
604
+ const angle = Math.atan2(dy, dx);
605
+ const displacementAmount = waveFactor * bulgeIntensity;
606
+ offsetX = Math.cos(angle) * displacementAmount;
607
+ offsetY = Math.sin(angle) * displacementAmount;
608
+ sizeMultiplier = 1 + waveFactor * 0.8;
609
+ bulgeOpacity = 0.3 + waveFactor * 0.7;
610
+ }
611
+ else if (bulgeType === "wave") {
612
+ const diagonalLength = Math.sqrt(canvasWidth * canvasWidth + canvasHeight * canvasHeight);
613
+ const wavePosOnDiagonal = waveProgress * diagonalLength * 1.2;
614
+ const normalizedX = dot.x / canvasWidth;
615
+ const normalizedY = 1 - dot.y / canvasHeight;
616
+ const dotDiagonalPos = ((normalizedX + normalizedY) / 2) * diagonalLength;
617
+ const distanceToWaveFront = dotDiagonalPos - wavePosOnDiagonal;
618
+ const waveWidth = diagonalLength * 0.2;
619
+ const distanceNorm = Math.abs(distanceToWaveFront) / waveWidth;
620
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 3);
621
+ const perpendicularOffset = normalizedY - normalizedX;
622
+ const sCurvePhase = perpendicularOffset * Math.PI * 2;
623
+ const sCurveFactor = Math.sin(sCurvePhase + waveProgress * Math.PI * 2);
624
+ const baseDisplacement = waveFactor * bulgeIntensity;
625
+ const diagonalAngle = Math.PI / 4;
626
+ offsetX =
627
+ Math.cos(diagonalAngle) * baseDisplacement +
628
+ sCurveFactor * baseDisplacement * 0.5;
629
+ offsetY =
630
+ -Math.sin(diagonalAngle) * baseDisplacement +
631
+ sCurveFactor * baseDisplacement * 0.5;
632
+ sizeMultiplier = 1 + waveFactor * 0.6;
633
+ bulgeOpacity = 0.4 + waveFactor * 0.6;
634
+ }
635
+ }
636
+ ctx.fillStyle = dot.color;
637
+ ctx.globalAlpha = opacity * bulgeOpacity;
638
+ const adjustedSize = size * sizeMultiplier;
639
+ const sizeOffset = (adjustedSize - size) / 2;
640
+ ctx.fillRect(dot.x + offsetX - sizeOffset, dot.y + offsetY - sizeOffset, adjustedSize, adjustedSize);
641
+ }
642
+ });
643
+ }
644
+ else {
645
+ // Reverse animation when hover ends - only run if there's something to hide
646
+ if (hideStartProgressRef.current > 0) {
647
+ const elapsed = (Date.now() - hideStartTimeRef.current) / 1000;
648
+ // Use quadratic easing for faster hide (power of 2)
649
+ const hideSpeed = speed * 6; // Faster to handle max progress of 2.0
650
+ const hideProgress = elapsed ** 2 * hideSpeed;
651
+ // Reverse from the progress we had when hide started. Under
652
+ // reduced motion the grid is gone at once.
653
+ const reverseProgress = shouldAnimate
654
+ ? Math.max(0, hideStartProgressRef.current - hideProgress)
655
+ : 0;
656
+ if (reverseProgress > 0.01) {
657
+ // Small threshold to ensure completion
658
+ // Still have dots to hide
659
+ dots.forEach((dot) => {
660
+ const normalizedDistance = dot.distanceFromOrigin / maxDistance;
661
+ const introOffset = normalizedDistance * 0.8 + dot.randomOffset * 0.5;
662
+ let opacity = 0;
663
+ if (reverseProgress > introOffset) {
664
+ const fadeIn = (reverseProgress - introOffset) * 8;
665
+ opacity = Math.min(1, fadeIn * fadeIn) * dot.baseOpacity;
666
+ // Apply flicker effect if enabled
667
+ if (flickering) {
668
+ const flickerValue = Math.sin(time * dot.flickerSpeed * 3 + dot.flickerPhase);
669
+ const flickerMultiplier = 0.6 + flickerValue * 0.4;
670
+ opacity *= flickerMultiplier;
671
+ }
672
+ }
673
+ if (opacity > 0) {
674
+ // Calculate bulge displacement
675
+ let offsetX = 0;
676
+ let offsetY = 0;
677
+ let sizeMultiplier = 1;
678
+ let bulgeOpacity = 1;
679
+ if (bulgeEnabled) {
680
+ const dx = dot.x - centerX;
681
+ const dy = dot.y - centerY;
682
+ const distanceFromCenter = Math.sqrt(dx * dx + dy * dy);
683
+ const distanceToWave = Math.abs(distanceFromCenter - waveRadius);
684
+ const waveWidth = maxRadius * 0.15;
685
+ const distanceNorm = distanceToWave / waveWidth;
686
+ const waveFactor = Math.exp(-distanceNorm * distanceNorm * 4);
687
+ const angle = Math.atan2(dy, dx);
688
+ const displacementAmount = waveFactor * bulgeIntensity;
689
+ offsetX = Math.cos(angle) * displacementAmount * 0.3;
690
+ offsetY =
691
+ Math.sin(angle) * displacementAmount * 0.3 - waveFactor * bulgeIntensity;
692
+ sizeMultiplier = 1 + waveFactor * 0.8;
693
+ bulgeOpacity = 0.3 + waveFactor * 0.7;
694
+ }
695
+ ctx.fillStyle = dot.color;
696
+ ctx.globalAlpha = opacity * bulgeOpacity;
697
+ const adjustedSize = size * sizeMultiplier;
698
+ const sizeOffset = (adjustedSize - size) / 2;
699
+ ctx.fillRect(dot.x + offsetX - sizeOffset, dot.y + offsetY - sizeOffset, adjustedSize, adjustedSize);
700
+ }
701
+ });
702
+ }
703
+ else {
704
+ // Hide animation complete, reset progress and clear canvas
705
+ hideStartProgressRef.current = 0;
706
+ }
707
+ }
708
+ }
709
+ }
710
+ ctx.globalAlpha = 1;
711
+ // Only continue animating if there's active animation or dynamic content
712
+ // Under reduced motion a revealed grid is drawn in one frame, so
713
+ // there is nothing more to animate while it stays revealed.
714
+ const hasActiveAnimation = (isHoveredRef.current && shouldAnimate) || hideStartProgressRef.current > 0;
715
+ const hasDynamicContent = flickering || (bulgeEnabled && showBulge);
716
+ if (hasActiveAnimation || hasDynamicContent) {
717
+ animationRef.current = requestAnimationFrame(animate);
718
+ }
719
+ else {
720
+ // Clear the ref so the animation can be restarted
721
+ animationRef.current = undefined;
722
+ }
723
+ };
724
+ // Store animate function in ref so it can be restarted
725
+ animateFnRef.current = animate;
726
+ animate();
727
+ };
728
+ setup();
729
+ const resizeObserver = new ResizeObserver(handleResize);
730
+ resizeObserver.observe(container);
731
+ return () => {
732
+ disposed = true;
733
+ resizeObserver.disconnect();
734
+ window.removeEventListener("resize", handleResize);
735
+ if (animationRef.current) {
736
+ cancelAnimationFrame(animationRef.current);
737
+ }
738
+ };
739
+ }, [colors, size, spacing, speed, revealFrom, trigger, flicker, bulge, fps, shouldAnimate]);
740
+ // Manual trigger control via `active` prop
741
+ useEffect(() => {
742
+ if (trigger !== "manual")
743
+ return;
744
+ const now = Date.now();
745
+ if (active) {
746
+ // Mimic mouse enter
747
+ if (hideStartProgressRef.current > 0) {
748
+ const hideElapsed = (now - hideStartTimeRef.current) / 1000;
749
+ const hideSpeed = speed * 6;
750
+ const hideProgress = hideElapsed ** 2 * hideSpeed;
751
+ const currentProgress = Math.max(0, hideStartProgressRef.current - hideProgress);
752
+ const effectiveElapsed = (currentProgress / (speed * 3)) ** (1 / 3);
753
+ const simulatedStartTime = now - effectiveElapsed * 1000;
754
+ revealStartTimeRef.current = simulatedStartTime;
755
+ }
756
+ else {
757
+ revealStartTimeRef.current = now;
758
+ }
759
+ if (bulge && !bulge.repeat) {
760
+ bulgeStartTimeRef.current = now;
761
+ }
762
+ isHoveredRef.current = true;
763
+ hideStartProgressRef.current = 0;
764
+ isStaticRef.current = false; // Invalidate cache
765
+ // Restart animation loop if it was stopped
766
+ if (!animationRef.current && animateFnRef.current) {
767
+ animationRef.current = requestAnimationFrame(animateFnRef.current);
768
+ }
769
+ }
770
+ else {
771
+ // Mimic mouse leave
772
+ if (isHoveredRef.current) {
773
+ const currentProgress = maxRevealProgressRef.current;
774
+ hideStartTimeRef.current = Date.now();
775
+ hideStartProgressRef.current = currentProgress;
776
+ isHoveredRef.current = false;
777
+ // Restart animation loop if it was stopped (for hide animation)
778
+ if (!animationRef.current && animateFnRef.current) {
779
+ animationRef.current = requestAnimationFrame(animateFnRef.current);
780
+ }
781
+ }
782
+ }
783
+ }, [active, trigger, speed, bulge]);
784
+ const handleMouseEnter = () => {
785
+ if (trigger === "hover" && !isHoveredRef.current) {
786
+ const now = Date.now();
787
+ // If we're currently hiding, resume from where we left off
788
+ if (hideStartProgressRef.current > 0) {
789
+ // Calculate current position during hide
790
+ const hideElapsed = (now - hideStartTimeRef.current) / 1000;
791
+ const hideSpeed = speed * 6;
792
+ const hideProgress = hideElapsed ** 2 * hideSpeed;
793
+ const currentProgress = Math.max(0, hideStartProgressRef.current - hideProgress);
794
+ // Reverse the cubic easing formula: progress = elapsed^3 * speed * 3
795
+ // So: elapsed = (progress / (speed * 3)) ^ (1/3)
796
+ const effectiveElapsed = (currentProgress / (speed * 3)) ** (1 / 3);
797
+ const simulatedStartTime = now - effectiveElapsed * 1000;
798
+ revealStartTimeRef.current = simulatedStartTime;
799
+ }
800
+ else {
801
+ // Fresh start
802
+ revealStartTimeRef.current = now;
803
+ }
804
+ // Reset bulge animation on each hover when repeat is false
805
+ if (bulge && !bulge.repeat) {
806
+ bulgeStartTimeRef.current = now;
807
+ }
808
+ isHoveredRef.current = true;
809
+ hideStartProgressRef.current = 0; // Clear hide state
810
+ isStaticRef.current = false; // Invalidate cache
811
+ // Restart animation loop if it was stopped
812
+ if (!animationRef.current && animateFnRef.current) {
813
+ animationRef.current = requestAnimationFrame(animateFnRef.current);
814
+ }
815
+ }
816
+ };
817
+ const handleMouseMove = () => {
818
+ // Recovery mechanism: if cursor is moving over the element but we're not in hover state, trigger it
819
+ if (trigger === "hover" && !isHoveredRef.current) {
820
+ handleMouseEnter();
821
+ }
822
+ };
823
+ const handleMouseLeave = () => {
824
+ if (trigger === "hover" && isHoveredRef.current) {
825
+ const currentProgress = maxRevealProgressRef.current;
826
+ hideStartTimeRef.current = Date.now();
827
+ hideStartProgressRef.current = currentProgress; // Capture current progress
828
+ isHoveredRef.current = false;
829
+ // Restart animation loop if it was stopped (for hide animation)
830
+ if (!animationRef.current && animateFnRef.current) {
831
+ animationRef.current = requestAnimationFrame(animateFnRef.current);
832
+ }
833
+ }
834
+ };
835
+ const handleClick = () => {
836
+ if (trigger !== "click")
837
+ return;
838
+ if (!isHoveredRef.current) {
839
+ // Enter
840
+ const now = Date.now();
841
+ if (hideStartProgressRef.current > 0) {
842
+ const hideElapsed = (now - hideStartTimeRef.current) / 1000;
843
+ const hideSpeed = speed * 6;
844
+ const hideProgress = hideElapsed ** 2 * hideSpeed;
845
+ const currentProgress = Math.max(0, hideStartProgressRef.current - hideProgress);
846
+ const effectiveElapsed = (currentProgress / (speed * 3)) ** (1 / 3);
847
+ const simulatedStartTime = now - effectiveElapsed * 1000;
848
+ revealStartTimeRef.current = simulatedStartTime;
849
+ }
850
+ else {
851
+ revealStartTimeRef.current = now;
852
+ }
853
+ if (bulge && !bulge.repeat) {
854
+ bulgeStartTimeRef.current = now;
855
+ }
856
+ isHoveredRef.current = true;
857
+ hideStartProgressRef.current = 0;
858
+ isStaticRef.current = false; // Invalidate cache
859
+ // Restart animation loop if it was stopped
860
+ if (!animationRef.current && animateFnRef.current) {
861
+ animationRef.current = requestAnimationFrame(animateFnRef.current);
862
+ }
863
+ }
864
+ else {
865
+ // Leave
866
+ const currentProgress = maxRevealProgressRef.current;
867
+ hideStartTimeRef.current = Date.now();
868
+ hideStartProgressRef.current = currentProgress;
869
+ isHoveredRef.current = false;
870
+ // Restart animation loop if it was stopped (for hide animation)
871
+ if (!animationRef.current && animateFnRef.current) {
872
+ animationRef.current = requestAnimationFrame(animateFnRef.current);
873
+ }
874
+ }
875
+ };
876
+ return (_jsxs(Flex, { ref: containerRef, fill: true, overflow: "hidden", onMouseEnter: handleMouseEnter, onMouseMove: handleMouseMove, onMouseLeave: handleMouseLeave, onClick: handleClick, ...rest, children: [_jsx("canvas", { ref: canvasRef, "aria-hidden": "true", style: {
877
+ position: "absolute",
878
+ top: 0,
879
+ left: 0,
880
+ width: "100%",
881
+ height: "100%",
882
+ pointerEvents: "none",
883
+ } }), children] }));
884
+ };
885
+ MatrixFx.displayName = "MatrixFx";
886
+ export { MatrixFx };