1"use client";
2
3import { useTheme } from "next-themes";
4import { useRef, useEffect, useMemo, useState, type CSSProperties } from "react";
5
6type PatternShape = "Checks" | "Stripes" | "Edge";
7
8const PatternShapes: Record<PatternShape, number> = {
9 Checks: 0,
10 Stripes: 1,
11 Edge: 2,
12};
13
14interface PresetColors {
15 color1: string;
16 color2: string;
17 color3: string;
18}
19
20interface PresetParams extends PresetColors {
21 rotation: number;
22 proportion: number;
23 scale: number;
24 speed: number;
25 distortion: number;
26 swirl: number;
27 swirlIterations: number;
28 softness: number;
29 offset: number;
30 shape: PatternShape;
31 shapeSize: number;
32 lightColors?: PresetColors;
33}
34
35const presets: Record<PresetName, PresetParams> = {
36 Prism: {
37 color1: "#050505",
38 color2: "#66B3FF",
39 color3: "#FFFFFF",
40 lightColors: {
41 color1: "#FAFAFA",
42 color2: "#66B3FF",
43 color3: "#050505",
44 },
45 rotation: -50,
46 proportion: 1,
47 scale: 0.01,
48 speed: 30,
49 distortion: 0,
50 swirl: 50,
51 swirlIterations: 16,
52 softness: 47,
53 offset: -299,
54 shape: "Checks",
55 shapeSize: 45,
56 },
57 Lava: {
58 color1: "#FF9F21",
59 color2: "#FF0303",
60 color3: "#000000",
61 lightColors: {
62 color1: "#FF9F21",
63 color2: "#FF0303",
64 color3: "#FAFAFA",
65 },
66 rotation: 114,
67 proportion: 100,
68 scale: 0.52,
69 speed: 30,
70 distortion: 7,
71 swirl: 18,
72 swirlIterations: 20,
73 softness: 100,
74 offset: 717,
75 shape: "Edge",
76 shapeSize: 12,
77 },
78 Plasma: {
79 color1: "#B566FF",
80 color2: "#000000",
81 color3: "#000000",
82 lightColors: {
83 color1: "#B566FF",
84 color2: "#FAFAFA",
85 color3: "#FAFAFA",
86 },
87 rotation: 0,
88 proportion: 63,
89 scale: 0.75,
90 speed: 30,
91 distortion: 5,
92 swirl: 61,
93 swirlIterations: 5,
94 softness: 100,
95 offset: -168,
96 shape: "Checks",
97 shapeSize: 28,
98 },
99 Pulse: {
100 color1: "#66FF85",
101 color2: "#000000",
102 color3: "#000000",
103 lightColors: {
104 color1: "#66FF85",
105 color2: "#FAFAFA",
106 color3: "#FAFAFA",
107 },
108 rotation: -167,
109 proportion: 92,
110 scale: 0,
111 speed: 20,
112 distortion: 54,
113 swirl: 75,
114 swirlIterations: 3,
115 softness: 28,
116 offset: -813,
117 shape: "Checks",
118 shapeSize: 79,
119 },
120 Vortex: {
121 color1: "#000000",
122 color2: "#FFFFFF",
123 color3: "#000000",
124 lightColors: {
125 color1: "#FAFAFA",
126 color2: "#000000",
127 color3: "#FAFAFA",
128 },
129 rotation: 50,
130 proportion: 41,
131 scale: 0.4,
132 speed: 20,
133 distortion: 0,
134 swirl: 100,
135 swirlIterations: 3,
136 softness: 5,
137 offset: -744,
138 shape: "Stripes",
139 shapeSize: 80,
140 },
141 Mist: {
142 color1: "#050505",
143 color2: "#FF66B8",
144 color3: "#050505",
145 lightColors: {
146 color1: "#FAFAFA",
147 color2: "#FF66B8",
148 color3: "#FAFAFA",
149 },
150 rotation: 0,
151 proportion: 33,
152 scale: 0.48,
153 speed: 39,
154 distortion: 4,
155 swirl: 65,
156 swirlIterations: 5,
157 softness: 100,
158 offset: -235,
159 shape: "Edge",
160 shapeSize: 48,
161 },
162};
163
164type PresetName = "Prism" | "Lava" | "Plasma" | "Pulse" | "Vortex" | "Mist";
165
166interface CustomConfig {
167 preset: "custom";
168 color1: string;
169 color2: string;
170 color3: string;
171 rotation?: number;
172 proportion?: number;
173 scale?: number;
174 speed?: number;
175 distortion?: number;
176 swirl?: number;
177 swirlIterations?: number;
178 softness?: number;
179 offset?: number;
180 shape?: PatternShape;
181 shapeSize?: number;
182}
183
184interface PresetConfig {
185 preset: PresetName;
186 speed?: number;
187}
188
189type GradientConfig = CustomConfig | PresetConfig;
190
191interface NoiseConfig {
192 opacity: number;
193 scale?: number;
194}
195
196interface AnimatedGradientProps {
197 config?: GradientConfig;
198 noise?: NoiseConfig;
199 radius?: string;
200 style?: CSSProperties;
201 className?: string;
202}
203
204export default function AnimatedGradient({
205 config = { preset: "Prism" },
206 noise,
207 radius = "0px",
208 style,
209 className,
210}: AnimatedGradientProps) {
211 const canvasRef = useRef<HTMLCanvasElement>(null);
212 const containerRef = useRef<HTMLDivElement>(null);
213 const frameIdRef = useRef<number | undefined>(undefined);
214 const startTimeRef = useRef<number>(0);
215
216 const [isMounted, setIsMounted] = useState(false);
217 const { resolvedTheme } = useTheme();
218
219 useEffect(() => {
220 setIsMounted(true);
221 return () => setIsMounted(false);
222 }, []);
223
224 const params = useMemo((): PresetParams => {
225 if (config.preset === "custom") {
226 return {
227 color1: config.color1,
228 color2: config.color2,
229 color3: config.color3,
230 rotation: config.rotation ?? 0,
231 proportion: config.proportion ?? 35,
232 scale: config.scale ?? 1,
233 speed: config.speed ?? 25,
234 distortion: config.distortion ?? 12,
235 swirl: config.swirl ?? 80,
236 swirlIterations: config.swirlIterations ?? 10,
237 softness: config.softness ?? 100,
238 offset: config.offset ?? 0,
239 shape: config.shape ?? "Checks",
240 shapeSize: config.shapeSize ?? 10,
241 };
242 }
243 const preset = presets[config.preset] || presets.Prism;
244 const useLight = isMounted && resolvedTheme === "light" && preset.lightColors;
245 return {
246 ...preset,
247 ...(useLight ? preset.lightColors : null),
248 speed: config.speed ?? preset.speed,
249 };
250 }, [config, isMounted, resolvedTheme]);
251
252 useEffect(() => {
253 const canvas = canvasRef.current;
254 const container = containerRef.current;
255 if (!canvas || !container || !isMounted) return;
256
257 const gl = canvas.getContext("webgl2", {
258 premultipliedAlpha: true,
259 alpha: true,
260 antialias: true,
261 });
262 if (!gl) return;
263
264 const vertexShaderSource = `#version 300 es
265 in vec4 a_position;
266 void main() {
267 gl_Position = a_position;
268 }`;
269
270 const vertexShader = gl.createShader(gl.VERTEX_SHADER)!;
271 gl.shaderSource(vertexShader, vertexShaderSource);
272 gl.compileShader(vertexShader);
273
274 const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)!;
275 gl.shaderSource(fragmentShader, FRAGMENT_SHADER);
276 gl.compileShader(fragmentShader);
277
278 const program = gl.createProgram()!;
279 gl.attachShader(program, vertexShader);
280 gl.attachShader(program, fragmentShader);
281 gl.linkProgram(program);
282 gl.useProgram(program);
283
284 const positionBuffer = gl.createBuffer();
285 gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
286 gl.bufferData(
287 gl.ARRAY_BUFFER,
288 new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
289 gl.STATIC_DRAW
290 );
291
292 const positionLocation = gl.getAttribLocation(program, "a_position");
293 gl.enableVertexAttribArray(positionLocation);
294 gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
295
296 const uniforms = {
297 u_time: gl.getUniformLocation(program, "u_time"),
298 u_resolution: gl.getUniformLocation(program, "u_resolution"),
299 u_pixelRatio: gl.getUniformLocation(program, "u_pixelRatio"),
300 u_scale: gl.getUniformLocation(program, "u_scale"),
301 u_rotation: gl.getUniformLocation(program, "u_rotation"),
302 u_color1: gl.getUniformLocation(program, "u_color1"),
303 u_color2: gl.getUniformLocation(program, "u_color2"),
304 u_color3: gl.getUniformLocation(program, "u_color3"),
305 u_proportion: gl.getUniformLocation(program, "u_proportion"),
306 u_softness: gl.getUniformLocation(program, "u_softness"),
307 u_shape: gl.getUniformLocation(program, "u_shape"),
308 u_shapeScale: gl.getUniformLocation(program, "u_shapeScale"),
309 u_distortion: gl.getUniformLocation(program, "u_distortion"),
310 u_swirl: gl.getUniformLocation(program, "u_swirl"),
311 u_swirlIterations: gl.getUniformLocation(program, "u_swirlIterations"),
312 };
313
314 const resize = () => {
315 const width = container.clientWidth;
316 const height = container.clientHeight;
317 const pixelRatio = window.devicePixelRatio || 1;
318 canvas.width = width * pixelRatio;
319 canvas.height = height * pixelRatio;
320 canvas.style.width = `${width}px`;
321 canvas.style.height = `${height}px`;
322 gl.viewport(0, 0, canvas.width, canvas.height);
323 };
324
325 resize();
326 const resizeObserver = new ResizeObserver(resize);
327 resizeObserver.observe(container);
328
329 startTimeRef.current = performance.now();
330
331 const animate = (time: number) => {
332 const elapsed = (time - startTimeRef.current) / 1000;
333 const speed = (params.speed / 100) * 5;
334
335 gl.uniform1f(uniforms.u_time, elapsed * speed + params.offset * 0.01);
336 gl.uniform2f(uniforms.u_resolution, canvas.width, canvas.height);
337 gl.uniform1f(uniforms.u_pixelRatio, window.devicePixelRatio || 1);
338 gl.uniform1f(uniforms.u_scale, params.scale);
339 gl.uniform1f(uniforms.u_rotation, (params.rotation * Math.PI) / 180);
340
341 const c1 = hexToRgba(params.color1);
342 const c2 = hexToRgba(params.color2);
343 const c3 = hexToRgba(params.color3);
344 gl.uniform4f(uniforms.u_color1, c1[0], c1[1], c1[2], c1[3]);
345 gl.uniform4f(uniforms.u_color2, c2[0], c2[1], c2[2], c2[3]);
346 gl.uniform4f(uniforms.u_color3, c3[0], c3[1], c3[2], c3[3]);
347
348 gl.uniform1f(uniforms.u_proportion, params.proportion / 100);
349 gl.uniform1f(uniforms.u_softness, params.softness / 100);
350 gl.uniform1f(uniforms.u_shape, PatternShapes[params.shape]);
351 gl.uniform1f(uniforms.u_shapeScale, params.shapeSize / 100);
352 gl.uniform1f(uniforms.u_distortion, params.distortion / 50);
353 gl.uniform1f(uniforms.u_swirl, params.swirl / 100);
354 gl.uniform1f(
355 uniforms.u_swirlIterations,
356 params.swirl === 0 ? 0 : params.swirlIterations
357 );
358
359 gl.drawArrays(gl.TRIANGLES, 0, 6);
360 frameIdRef.current = requestAnimationFrame(animate);
361 };
362
363 frameIdRef.current = requestAnimationFrame(animate);
364
365 return () => {
366 if (frameIdRef.current !== undefined) {
367 cancelAnimationFrame(frameIdRef.current);
368 }
369 resizeObserver.disconnect();
370 gl.deleteProgram(program);
371 gl.deleteShader(vertexShader);
372 gl.deleteShader(fragmentShader);
373 gl.deleteBuffer(positionBuffer);
374 };
375 }, [isMounted, params]);
376
377 return (
378 <div
379 ref={containerRef}
380 className={className}
381 style={{
382 position: "absolute",
383 inset: 0,
384 zIndex: -1,
385 borderRadius: radius,
386 overflow: "hidden",
387 ...style,
388 }}
389 >
390 <canvas
391 ref={canvasRef}
392 style={{
393 display: "block",
394 width: "100%",
395 height: "100%",
396 }}
397 />
398 {noise && noise.opacity > 0 && (
399 <div
400 style={{
401 position: "absolute",
402 inset: 0,
403 backgroundImage: `url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAElBMVEUAAAAAAAAAAAAAAAAAAAAAAADgKxmiAAAABnRSTlMCCgkGBAVJOAVJAAAASklEQVQ4y2NgGAWjYBSMglEwCgY/YGRgZBQUYmJiZGQEkYwMjIyMgoKCjIyMIJKBgRFIMjIyAklGRkYGRkFBYEcwMDIyMjAOUQAA1I4HwVwZAkYAAAAASUVORK5CYII=")`,
404 backgroundSize: (noise.scale ?? 1) * 200,
405 backgroundRepeat: "repeat",
406 opacity: noise.opacity / 2,
407 pointerEvents: "none",
408 }}
409 />
410 )}
411 </div>
412 );
413}
414
415function hexToRgba(hex: string): [number, number, number, number] {
416 let r = 0,
417 g = 0,
418 b = 0,
419 a = 1;
420
421 if (hex.startsWith("rgba(")) {
422 const parts = hex.slice(5, -1).split(",");
423 r = parseInt(parts[0]) / 255;
424 g = parseInt(parts[1]) / 255;
425 b = parseInt(parts[2]) / 255;
426 a = parseFloat(parts[3]);
427 } else if (hex.startsWith("rgb(")) {
428 const parts = hex.slice(4, -1).split(",");
429 r = parseInt(parts[0]) / 255;
430 g = parseInt(parts[1]) / 255;
431 b = parseInt(parts[2]) / 255;
432 } else if (hex.startsWith("hsla(") || hex.startsWith("hsl(")) {
433 const isHsla = hex.startsWith("hsla(");
434 const parts = hex.slice(isHsla ? 5 : 4, -1).split(",");
435 const h = parseFloat(parts[0]) / 360;
436 const s = parseFloat(parts[1]) / 100;
437 const l = parseFloat(parts[2]) / 100;
438 a = isHsla ? parseFloat(parts[3]) : 1;
439 [r, g, b] = hslToRgb(h, s, l);
440 } else if (hex.startsWith("#")) {
441 const c = hex.slice(1);
442 if (c.length === 3) {
443 r = parseInt(c[0] + c[0], 16) / 255;
444 g = parseInt(c[1] + c[1], 16) / 255;
445 b = parseInt(c[2] + c[2], 16) / 255;
446 } else if (c.length >= 6) {
447 r = parseInt(c.slice(0, 2), 16) / 255;
448 g = parseInt(c.slice(2, 4), 16) / 255;
449 b = parseInt(c.slice(4, 6), 16) / 255;
450 if (c.length === 8) {
451 a = parseInt(c.slice(6, 8), 16) / 255;
452 }
453 }
454 }
455
456 return [r, g, b, a];
457}
458
459function hslToRgb(h: number, s: number, l: number): [number, number, number] {
460 let r: number, g: number, b: number;
461
462 if (s === 0) {
463 r = g = b = l;
464 } else {
465 const hue2rgb = (p: number, q: number, t: number) => {
466 if (t < 0) t += 1;
467 if (t > 1) t -= 1;
468 if (t < 1 / 6) return p + (q - p) * 6 * t;
469 if (t < 1 / 2) return q;
470 if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
471 return p;
472 };
473
474 const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
475 const p = 2 * l - q;
476 r = hue2rgb(p, q, h + 1 / 3);
477 g = hue2rgb(p, q, h);
478 b = hue2rgb(p, q, h - 1 / 3);
479 }
480
481 return [r, g, b];
482}
483
484const FRAGMENT_SHADER = `#version 300 es
485precision highp float;
486
487uniform float u_time;
488uniform float u_pixelRatio;
489uniform vec2 u_resolution;
490
491uniform float u_scale;
492uniform float u_rotation;
493uniform vec4 u_color1;
494uniform vec4 u_color2;
495uniform vec4 u_color3;
496uniform float u_proportion;
497uniform float u_softness;
498uniform float u_shape;
499uniform float u_shapeScale;
500uniform float u_distortion;
501uniform float u_swirl;
502uniform float u_swirlIterations;
503
504out vec4 fragColor;
505
506#define TWO_PI 6.28318530718
507#define PI 3.14159265358979323846
508
509vec2 rotate(vec2 uv, float th) {
510 return mat2(cos(th), sin(th), -sin(th), cos(th)) * uv;
511}
512
513float random(vec2 st) {
514 return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453123);
515}
516
517float noise(vec2 st) {
518 vec2 i = floor(st);
519 vec2 f = fract(st);
520 float a = random(i);
521 float b = random(i + vec2(1.0, 0.0));
522 float c = random(i + vec2(0.0, 1.0));
523 float d = random(i + vec2(1.0, 1.0));
524
525 vec2 u = f * f * (3.0 - 2.0 * f);
526
527 float x1 = mix(a, b, u.x);
528 float x2 = mix(c, d, u.x);
529 return mix(x1, x2, u.y);
530}
531
532vec4 blend_colors(vec4 c1, vec4 c2, vec4 c3, float mixer, float edgesWidth, float edge_blur) {
533 vec3 color1 = c1.rgb * c1.a;
534 vec3 color2 = c2.rgb * c2.a;
535 vec3 color3 = c3.rgb * c3.a;
536
537 float r1 = smoothstep(.0 + .35 * edgesWidth, .7 - .35 * edgesWidth + .5 * edge_blur, mixer);
538 float r2 = smoothstep(.3 + .35 * edgesWidth, 1. - .35 * edgesWidth + edge_blur, mixer);
539
540 vec3 blended_color_2 = mix(color1, color2, r1);
541 float blended_opacity_2 = mix(c1.a, c2.a, r1);
542
543 vec3 c = mix(blended_color_2, color3, r2);
544 float o = mix(blended_opacity_2, c3.a, r2);
545 return vec4(c, o);
546}
547
548void main() {
549 vec2 uv = gl_FragCoord.xy / u_resolution.xy;
550
551 float t = .5 * u_time;
552
553 float noise_scale = .0005 + .006 * u_scale;
554
555 uv -= .5;
556 uv *= (noise_scale * u_resolution);
557 uv = rotate(uv, u_rotation * .5 * PI);
558 uv /= u_pixelRatio;
559 uv += .5;
560
561 float n1 = noise(uv * 1. + t);
562 float n2 = noise(uv * 2. - t);
563 float angle = n1 * TWO_PI;
564 uv.x += 4. * u_distortion * n2 * cos(angle);
565 uv.y += 4. * u_distortion * n2 * sin(angle);
566
567 float iterations_number = ceil(clamp(u_swirlIterations, 1., 30.));
568 for (float i = 1.; i <= iterations_number; i++) {
569 uv.x += clamp(u_swirl, 0., 2.) / i * cos(t + i * 1.5 * uv.y);
570 uv.y += clamp(u_swirl, 0., 2.) / i * cos(t + i * 1. * uv.x);
571 }
572
573 float proportion = clamp(u_proportion, 0., 1.);
574
575 float shape = 0.;
576 float mixer = 0.;
577 if (u_shape < .5) {
578 vec2 checks_shape_uv = uv * (.5 + 3.5 * u_shapeScale);
579 shape = .5 + .5 * sin(checks_shape_uv.x) * cos(checks_shape_uv.y);
580 mixer = shape + .48 * sign(proportion - .5) * pow(abs(proportion - .5), .5);
581 } else if (u_shape < 1.5) {
582 vec2 stripes_shape_uv = uv * (.25 + 3. * u_shapeScale);
583 float f = fract(stripes_shape_uv.y);
584 shape = smoothstep(.0, .55, f) * smoothstep(1., .45, f);
585 mixer = shape + .48 * sign(proportion - .5) * pow(abs(proportion - .5), .5);
586 } else {
587 float sh = 1. - uv.y;
588 sh -= .5;
589 sh /= (noise_scale * u_resolution.y);
590 sh += .5;
591 float shape_scaling = .2 * (1. - u_shapeScale);
592 shape = smoothstep(.45 - shape_scaling, .55 + shape_scaling, sh + .3 * (proportion - .5));
593 mixer = shape;
594 }
595
596 vec4 color_mix = blend_colors(u_color1, u_color2, u_color3, mixer, 1. - clamp(u_softness, 0., 1.), .01 + .01 * u_scale);
597
598 fragColor = vec4(color_mix.rgb, color_mix.a);
599}
600`;
601