feat(homepage+tools): tools page card refinement and homepage fixes

This commit is contained in:
2026-11-06 18:38:45 +05:30
parent 69d4195718
commit 1a2a3045f5
48 changed files with 4866 additions and 1450 deletions
@@ -0,0 +1,52 @@
'use client';
import React, { ComponentPropsWithoutRef } from 'react';
import { cn } from '@/lib/utils';
export interface AnimatedGradientTextProps extends ComponentPropsWithoutRef<'span'> {
speed?: number;
colorFrom?: string;
colorTo?: string;
pauseWhenHidden?: boolean;
}
/**
* Magic UI - Animated Gradient Text
* Liquid flowing gradient text with 0% idle CPU overhead.
* Reference: https://magicui.design/docs/components/animated-gradient-text
*/
export function AnimatedGradientText({
children,
className,
speed = 1,
colorFrom = '#2563eb',
colorTo = '#ec4899',
pauseWhenHidden = true,
style,
...props
}: AnimatedGradientTextProps) {
const duration = Math.max(2, 8 / speed);
return (
<span
style={{
'--bg-size': `${speed * 300}%`,
'--color-from': colorFrom,
'--color-to': colorTo,
backgroundImage: `linear-gradient(90deg, var(--color-from), var(--color-to), #8b5cf6, var(--color-from))`,
backgroundSize: '250% 100%',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
animationDuration: `${duration}s`,
...style,
} as React.CSSProperties}
className={cn(
'animate-gradient inline-block bg-clip-text text-transparent',
className
)}
{...props}
>
{children}
</span>
);
}
@@ -0,0 +1,59 @@
'use client';
import React, {
type ComponentPropsWithoutRef,
type CSSProperties,
type FC,
} from 'react';
import { cn } from '@/lib/utils';
export interface AnimatedShinyTextProps extends ComponentPropsWithoutRef<'span'> {
shimmerWidth?: number;
/**
* If true (default), shimmer animation only runs when the cursor is hovered over the text.
* Reference: https://magicui.design/docs/components/animated-shiny-text
*/
hoverOnly?: boolean;
}
/**
* Magic UI - Animated Shiny Text
* Subtle shimmering light reflection that passes smoothly across typography on hover.
* Zero CPU overhead when resting; activates only on cursor hover.
* Reference: https://magicui.design/docs/components/animated-shiny-text
*/
export const AnimatedShinyText = React.forwardRef<HTMLSpanElement, AnimatedShinyTextProps>(
(
{
children,
className,
shimmerWidth = 120,
hoverOnly = true,
style,
...props
},
ref
) => {
return (
<span
ref={ref}
style={
{
'--shiny-width': `${shimmerWidth}px`,
...style,
} as CSSProperties
}
className={cn(
hoverOnly ? 'studio-shiny-hover' : 'animate-shiny-text studio-shiny-always',
className
)}
{...props}
>
{children}
</span>
);
}
);
AnimatedShinyText.displayName = 'AnimatedShinyText';
export default AnimatedShinyText;
+49
View File
@@ -0,0 +1,49 @@
'use client';
import React, { memo } from 'react';
import { cn } from '@/lib/utils';
export interface AuroraTextProps {
children: React.ReactNode;
className?: string;
colors?: string[];
speed?: number;
}
/**
* Magic UI - Aurora Text
* A vibrant glowing aurora gradient text effect that shifts colors like the Northern Lights.
* Reference: https://magicui.design/docs/components/aurora-text
*/
export const AuroraText = memo(
({
children,
className = '',
colors = ['#2563eb', '#7c3aed', '#ec4899', '#06b6d4', '#3b82f6'],
speed = 1,
}: AuroraTextProps) => {
const gradientStyle: React.CSSProperties = {
backgroundImage: `linear-gradient(135deg, ${colors.join(', ')}, ${colors[0]})`,
backgroundSize: '220% auto',
WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
animationDuration: `${8 / speed}s`,
};
return (
<span className={cn('relative inline-block', className)}>
<span className="sr-only">{children}</span>
<span
className="animate-aurora relative inline-block bg-clip-text text-transparent"
style={gradientStyle}
aria-hidden="true"
>
{children}
</span>
</span>
);
}
);
AuroraText.displayName = 'AuroraText';
export default AuroraText;
+11 -11
View File
@@ -48,9 +48,9 @@ export function BentoCard({
const content = (
<div
className={cn(
'group relative col-span-1 flex flex-col justify-between overflow-hidden rounded-3xl',
'bg-white border border-slate-200/90 shadow-cream-sm',
'transform-gpu transition-all duration-300 hover:-translate-y-1 hover:shadow-cream-lg hover:border-blue-400/60',
'group relative col-span-1 flex flex-col justify-between overflow-hidden rounded-card',
'bg-paper-hi border border-rule shadow-sheet',
'motion-safe:transition-[transform,box-shadow,border-color] duration-300 hover:-translate-y-1 hover:border-accent',
className
)}
>
@@ -58,35 +58,35 @@ export function BentoCard({
<div className="absolute inset-0 z-0 overflow-hidden">{background}</div>
{/* Subtle Gradient Overlay */}
<div className="pointer-events-none absolute inset-0 z-10 bg-gradient-to-t from-slate-950/85 via-slate-950/25 to-transparent transition-opacity duration-300" />
<div className="pointer-events-none absolute inset-0 z-10 bg-gradient-to-t from-ink/90 via-ink/30 to-transparent transition-opacity duration-300" />
{/* Top Header Badge */}
<div className="relative z-20 flex items-center justify-between p-5">
{badge && (
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[10px] font-mono font-bold tracking-wider uppercase text-blue-700 bg-white/90 backdrop-blur-md border border-blue-200 shadow-sm">
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-body font-medium text-ink bg-paper-hi border border-rule shadow-sm">
{badge}
</span>
)}
{Icon && (
<div className="w-9 h-9 rounded-xl bg-white/90 backdrop-blur-md border border-slate-200/80 flex items-center justify-center text-blue-600 shadow-sm group-hover:scale-110 transition-transform">
<div className="w-9 h-9 rounded-md bg-paper-hi border border-rule flex items-center justify-center text-accent shadow-sm group-hover:scale-105 motion-safe:transition-transform">
<Icon className="w-4 h-4" />
</div>
)}
</div>
{/* Bottom Content Area */}
<div className="relative z-20 flex flex-col gap-2 p-6 text-white">
<h3 className="text-xl font-display font-bold text-white tracking-tight group-hover:text-blue-300 transition-colors">
<div className="relative z-20 flex flex-col gap-2 p-6 text-paper-hi">
<h3 className="text-xl font-display font-bold text-white tracking-tight group-hover:text-accent transition-colors">
{name}
</h3>
<p className="text-xs sm:text-sm text-slate-200 line-clamp-2 leading-relaxed">
<p className="text-xs sm:text-sm text-paper-2 line-clamp-2 leading-relaxed">
{description}
</p>
{href && (
<div className="pt-2 flex items-center gap-1 text-xs font-semibold text-blue-300 group-hover:text-white transition-colors">
<div className="pt-2 flex items-center gap-1.5 text-xs font-medium text-accent group-hover:text-white transition-colors">
<span>{cta}</span>
<ArrowRight className="w-3.5 h-3.5 transition-transform group-hover:translate-x-1" />
<ArrowRight className="w-3.5 h-3.5 motion-safe:transition-transform group-hover:translate-x-1" />
</div>
)}
</div>
+71
View File
@@ -0,0 +1,71 @@
'use client';
import React, { useRef, useState, useEffect } from 'react';
import { motion, useInView, Variants } from 'framer-motion';
import { cn } from '@/lib/utils';
interface BlurFadeProps {
children: React.ReactNode;
className?: string;
variant?: Variants;
duration?: number;
delay?: number;
yOffset?: number;
inView?: boolean;
inViewMargin?: string;
blur?: string;
}
/**
* Magic UI - Blur Fade
* Staggered cinematic reveal with smooth blur-in and vertical translation.
* Ensures text is always visible and never hidden if intersection observer delays.
* Reference: https://magicui.design/docs/components/blur-fade
*/
export function BlurFade({
children,
className,
variant,
duration = 0.45,
delay = 0,
yOffset = 10,
inView = true,
inViewMargin = '0px',
blur = '4px',
}: BlurFadeProps) {
const ref = useRef<HTMLDivElement>(null);
const [mounted, setMounted] = useState(false);
const inViewResult = useInView(ref, { once: true, margin: inViewMargin as any });
useEffect(() => {
// Guarantees visibility after initial mount
const timer = setTimeout(() => setMounted(true), 60);
return () => clearTimeout(timer);
}, []);
const isVisible = !inView || inViewResult || mounted;
const defaultVariants: Variants = {
hidden: { y: yOffset, opacity: 0, filter: `blur(${blur})` },
visible: { y: 0, opacity: 1, filter: 'blur(0px)' },
};
const combinedVariants = variant || defaultVariants;
return (
<motion.div
ref={ref}
initial="hidden"
animate={isVisible ? 'visible' : 'visible'}
variants={combinedVariants}
transition={{
delay: 0.02 + delay,
duration,
ease: [0.16, 1, 0.3, 1],
}}
className={cn(className)}
>
{children}
</motion.div>
);
}
+51 -8
View File
@@ -1,6 +1,6 @@
'use client';
import React from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils';
interface BorderBeamProps {
@@ -14,18 +14,54 @@ interface BorderBeamProps {
delay?: number;
}
/**
* Magic UI - Border Beam
* Animated traveling light border beam.
* Optimized with IntersectionObserver to sleep when out of view,
* and falls back to a clean static gradient on mobile/touch to eliminate GPU heating.
* Reference: https://magicui.design/docs/components/border-beam
*/
export function BorderBeam({
className,
size = 250,
duration = 12,
borderWidth = 1.5,
anchor = 90,
colorFrom = '#3b82f6',
colorTo = '#8b5cf6',
colorFrom = 'var(--color-accent)',
colorTo = 'var(--color-accent-hi)',
delay = 0,
}: BorderBeamProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [isVisible, setIsVisible] = useState(false);
const [isTouchDevice, setIsTouchDevice] = useState(false);
useEffect(() => {
// Detect mobile touch devices to eliminate GPU-churning conic masks
if (typeof window !== 'undefined') {
const isTouch =
window.innerWidth < 1024 ||
navigator.maxTouchPoints > 0 ||
'ontouchstart' in window;
setIsTouchDevice(isTouch);
}
const container = containerRef.current;
if (!container) return;
const observer = new IntersectionObserver(
([entry]) => {
setIsVisible(entry.isIntersecting);
},
{ threshold: 0.05 }
);
observer.observe(container);
return () => observer.disconnect();
}, []);
return (
<div
ref={containerRef}
style={
{
'--size': `${size}px`,
@@ -38,7 +74,7 @@ export function BorderBeam({
} as React.CSSProperties
}
className={cn(
'pointer-events-none absolute inset-0 rounded-[inherit] overflow-hidden',
'pointer-events-none absolute inset-0 rounded-[inherit] overflow-hidden motion-reduce:hidden',
className
)}
>
@@ -46,21 +82,28 @@ export function BorderBeam({
className="absolute inset-0 rounded-[inherit]"
style={{
padding: `${borderWidth}px`,
mask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
WebkitMask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
mask: 'linear-gradient(currentColor 0 0) content-box, linear-gradient(currentColor 0 0)',
WebkitMask: 'linear-gradient(currentColor 0 0) content-box, linear-gradient(currentColor 0 0)',
maskComposite: 'exclude',
WebkitMaskComposite: 'xor',
}}
>
<div
className="absolute inset-[-100%] animate-spin pointer-events-none"
className={cn(
'absolute inset-[-100%] pointer-events-none',
isVisible && !isTouchDevice && 'animate-spin'
)}
style={{
animationDuration: `${duration}s`,
animationDelay: `${delay}s`,
background: `conic-gradient(from 0deg at 50% 50%, transparent 0deg, transparent 270deg, ${colorFrom} 315deg, ${colorTo} 360deg)`,
willChange: isVisible && !isTouchDevice ? 'transform' : 'auto',
transform: 'translateZ(0)',
background: `conic-gradient(from 0deg at 50% 50%, transparent 0deg, transparent 270deg, var(--color-from) 315deg, var(--color-to) 360deg)`,
}}
/>
</div>
</div>
);
}
export default BorderBeam;
+276
View File
@@ -0,0 +1,276 @@
'use client';
import React, { useEffect, useRef, useState, type ReactNode } from 'react';
import {
animate,
motion,
useInView,
useMotionValue,
useReducedMotion,
useTransform,
type HTMLMotionProps,
} from 'framer-motion';
import { cn } from '@/lib/utils';
const DEFAULT_COLORS = ['#c679c4', '#fa3d1d', '#ffb005', '#e1e1fe', '#0358f7'];
const BAND_HALF = 17;
const SWEEP_START = -BAND_HALF;
const SWEEP_END = 100 + BAND_HALF;
const sweepEase = (t: number) =>
t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;
function buildGradient(pos: number, colors: string[], textColor: string) {
const bandStart = pos - BAND_HALF;
const bandEnd = pos + BAND_HALF;
if (bandStart >= 100) {
return `linear-gradient(90deg, ${textColor}, ${textColor})`;
}
const n = colors.length;
const parts: string[] = [];
if (bandStart > 0) {
parts.push(`${textColor} 0%`, `${textColor} ${bandStart.toFixed(2)}%`);
}
colors.forEach((c, i) => {
const pct = n === 1 ? pos : bandStart + (i / (n - 1)) * BAND_HALF * 2;
parts.push(`${c} ${pct.toFixed(2)}%`);
});
if (bandEnd < 100) {
parts.push(`transparent ${bandEnd.toFixed(2)}%`, `transparent 100%`);
}
return `linear-gradient(90deg, ${parts.join(', ')})`;
}
function measureWidths(el: HTMLElement, texts: string[]) {
if (!el.parentElement) return texts.map(() => 0);
const ghost = el.cloneNode() as HTMLElement;
Object.assign(ghost.style, {
position: 'absolute',
visibility: 'hidden',
pointerEvents: 'none',
width: 'auto',
whiteSpace: 'nowrap',
});
el.parentElement.appendChild(ghost);
const widths = texts.map((t) => {
ghost.textContent = t;
return ghost.getBoundingClientRect().width;
});
ghost.remove();
return widths;
}
export interface DiaTextRevealProps extends Omit<
HTMLMotionProps<'span'>,
'ref' | 'children' | 'style' | 'animate' | 'transition' | 'color'
> {
text?: string | string[];
children?: ReactNode;
colors?: string[];
textColor?: string;
duration?: number;
delay?: number;
repeat?: boolean;
repeatDelay?: number;
startOnView?: boolean;
once?: boolean;
className?: string;
fixedWidth?: boolean;
hoverShiny?: boolean;
}
/**
* Magic UI - Dia Text Reveal
* - At first: Horizontal radiant gradient sweep reveals text as it enters viewport or mounts.
* - On hover: Magic UI Animated Shiny Text specular light reflection.
* Reference: https://magicui.design/docs/components/dia-text-reveal
* Reference: https://magicui.design/docs/components/animated-shiny-text
*/
export function DiaTextReveal({
text,
children,
colors = DEFAULT_COLORS,
textColor = 'var(--color-ink)',
duration = 1.3,
delay = 0.05,
repeat = false,
repeatDelay = 0.5,
startOnView = true,
once = true,
className,
fixedWidth = false,
hoverShiny = true,
...props
}: DiaTextRevealProps) {
const resolvedText = React.useMemo(() => {
if (text != null) {
return Array.isArray(text) ? text : [text];
}
if (typeof children === 'string') {
return [children];
}
if (Array.isArray(children)) {
const flat = children.map((c) => (typeof c === 'string' ? c : '')).join('');
return [flat || ''];
}
if (children != null) {
return [String(children)];
}
return [''];
}, [text, children]);
const texts = resolvedText;
const isMulti = texts.length > 1;
const prefersReducedMotion = useReducedMotion();
const spanRef = useRef<HTMLSpanElement>(null);
const optsRef = useRef({
colors,
textColor,
duration,
delay,
repeat,
repeatDelay,
texts,
});
optsRef.current = {
colors,
textColor,
duration,
delay,
repeat,
repeatDelay,
texts,
};
const indexRef = useRef(0);
const hasPlayedRef = useRef(false);
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
const playRef = useRef<() => void>(null!);
const stopRef = useRef<(() => void) | null>(null);
const [activeIndex, setActiveIndex] = useState(0);
const [measuredWidths, setMeasuredWidths] = useState<number[]>([]);
const [isRevealed, setIsRevealed] = useState(false);
const sweepPos = useMotionValue(SWEEP_START);
const backgroundImage = useTransform(sweepPos, (pos) =>
buildGradient(pos, optsRef.current.colors, optsRef.current.textColor)
);
const isInView = useInView(spanRef, { once, amount: 0.1 });
useEffect(() => {
const el = spanRef.current;
if (!el || !isMulti) return;
setMeasuredWidths(measureWidths(el, texts));
}, [texts.join('\0'), isMulti]);
playRef.current = () => {
const { duration: dur, delay: dly, repeat: rpt, repeatDelay: rptDly, texts: txts } = optsRef.current;
setIsRevealed(false);
sweepPos.set(SWEEP_START);
const controls = animate(sweepPos, SWEEP_END, {
duration: dur,
delay: dly,
ease: sweepEase,
onComplete() {
setIsRevealed(true);
if (!rpt) return;
timerRef.current = setTimeout(() => {
const next = (indexRef.current + 1) % txts.length;
indexRef.current = next;
setActiveIndex(next);
playRef.current();
}, rptDly * 1000);
},
});
stopRef.current = () => controls.stop();
};
// Viewport trigger: plays once when scrolled into view (or immediately if in initial viewport)
useEffect(() => {
if (prefersReducedMotion) {
sweepPos.set(SWEEP_END);
setIsRevealed(true);
return;
}
if (startOnView && !isInView) return;
if (once && hasPlayedRef.current) return;
hasPlayedRef.current = true;
playRef.current();
// Safety fallback: if animation interrupted, ensure text reveals
const safetyTimer = setTimeout(() => {
setIsRevealed(true);
}, (optsRef.current.duration + optsRef.current.delay + 0.4) * 1000);
return () => {
stopRef.current?.();
clearTimeout(timerRef.current);
clearTimeout(safetyTimer);
};
}, [isInView, startOnView, once, prefersReducedMotion]);
const fixedW =
isMulti && fixedWidth && measuredWidths.length > 0
? Math.max(...measuredWidths)
: undefined;
const animatedW =
isMulti && !fixedWidth && measuredWidths[activeIndex] != null
? measuredWidths[activeIndex]
: undefined;
return (
<motion.span
ref={spanRef}
className={cn(
'inline-block align-bottom leading-[1.1] select-none',
isRevealed ? (hoverShiny ? 'studio-shiny-hover cursor-pointer' : 'cursor-default') : 'cursor-default',
className
)}
style={{
...(isMulti && {
display: 'inline-block',
overflow: 'hidden',
whiteSpace: 'nowrap',
...(fixedW != null && { width: fixedW }),
}),
...(isRevealed
? {
color: textColor,
WebkitTextFillColor: 'currentColor',
backgroundImage: 'none',
backgroundClip: 'unset',
WebkitBackgroundClip: 'unset',
}
: {
color: 'transparent',
WebkitTextFillColor: 'transparent',
backgroundClip: 'text',
WebkitBackgroundClip: 'text',
backgroundSize: '100% 100%',
backgroundImage,
}),
}}
animate={animatedW != null ? { width: animatedW } : undefined}
transition={{ duration: 0.4, ease: [0.4, 0, 0.2, 1] }}
{...props}
>
{texts[activeIndex]}
</motion.span>
);
}
export default DiaTextReveal;
@@ -0,0 +1,75 @@
'use client';
import React from 'react';
import { ArrowRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface InteractiveHoverButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
text?: string;
href?: string;
}
/**
* Magic UI - Interactive Hover Button
* Tactile pill button with smooth accent fill on desktop hover and instant haptic feedback on mobile.
* Reference: https://magicui.design/docs/components/interactive-hover-button
*/
export const InteractiveHoverButton = React.forwardRef<
HTMLButtonElement,
InteractiveHoverButtonProps
>(({ text = 'Explore Studio', href, className, children, ...props }, ref) => {
const label = text || children;
const content = (
<>
{/* Background fill layer: smooth full-pill expansion on desktop hover without any blue-and-white cutoffs */}
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 rounded-full bg-accent opacity-0 transition-opacity duration-300 ease-out [@media(hover:hover)]:group-hover:opacity-100"
style={{ borderRadius: 9999 }}
/>
{/* Default Content: Blue dot + Label */}
<span className="relative z-10 flex items-center justify-center gap-2.5 transition-all duration-300 [@media(hover:hover)]:group-hover:opacity-0 [@media(hover:hover)]:group-hover:translate-x-3">
<span className="h-2 w-2 rounded-full bg-accent shrink-0 transition-transform duration-300 [@media(hover:hover)]:group-hover:scale-150" />
<span className="font-bold text-ink">{label}</span>
</span>
{/* Hover Content: White text + Arrow sliding into view (only on desktop pointer hover) */}
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center gap-2 text-accent-ink font-bold opacity-0 -translate-x-3 transition-all duration-300 [@media(hover:hover)]:group-hover:opacity-100 [@media(hover:hover)]:group-hover:translate-x-0"
>
<span>{label}</span>
<ArrowRight className="w-4 h-4 ml-0.5" />
</span>
</>
);
const baseClasses = cn(
'group relative inline-flex items-center justify-center border border-rule/90',
'bg-paper-hi text-ink font-body text-sm sm:text-base font-bold shadow-xs',
'min-h-[48px] px-6 sm:px-7 py-3 cursor-pointer select-none [border-radius:9999px] overflow-hidden',
'focus-visible:ring-2 focus-visible:ring-accent active:scale-[0.98]',
'disabled:opacity-50 disabled:pointer-events-none transition-colors duration-200',
'hover:border-accent hover:shadow-glow active:bg-paper-2',
className
);
if (href) {
return (
<a href={href} className={baseClasses} style={{ borderRadius: 9999 }}>
{content}
</a>
);
}
return (
<button ref={ref} className={baseClasses} style={{ borderRadius: 9999 }} {...props}>
{content}
</button>
);
});
InteractiveHoverButton.displayName = 'InteractiveHoverButton';
+42
View File
@@ -0,0 +1,42 @@
'use client';
import React from 'react';
import { DiaTextReveal, DiaTextRevealProps } from './dia-text-reveal';
export type KineticTextProps = DiaTextRevealProps;
/**
* Universal Section Heading Component:
* - At first (when entering viewport / on mount): Magic UI Dia Text Reveal (radiant gradient sweep)
* - On hover: Magic UI Animated Shiny Text (specular light glare shimmer reflection)
* Reference: https://magicui.design/docs/components/dia-text-reveal
* Reference: https://magicui.design/docs/components/animated-shiny-text
*/
export function KineticText({
children,
text,
className,
delay = 0.05,
duration = 1.3,
colors,
textColor = 'var(--color-ink)',
hoverShiny = true,
...rest
}: KineticTextProps) {
return (
<DiaTextReveal
text={text}
className={className}
delay={delay}
duration={duration}
colors={colors}
textColor={textColor}
hoverShiny={hoverShiny}
{...rest}
>
{children}
</DiaTextReveal>
);
}
export default KineticText;
+60
View File
@@ -0,0 +1,60 @@
'use client';
import React from 'react';
import { cn } from '@/lib/utils';
interface LightRaysProps {
className?: string;
count?: number;
color?: string;
}
/**
* Magic UI - Light Rays
* Volumetric studio light rays that radiate across the canvas with subtle atmospheric depth.
* Reference: https://magicui.design/docs/components/light-rays
*/
export function LightRays({
className,
count = 7,
color = 'var(--color-accent)',
}: LightRaysProps) {
return (
<div
aria-hidden="true"
className={cn(
'pointer-events-none absolute inset-0 overflow-hidden select-none',
className
)}
>
{/* Light origin radial bloom */}
<div
className="absolute -top-32 left-1/2 -translate-x-1/2 w-[700px] h-[350px] [background:radial-gradient(ellipse_at_top,color-mix(in_oklab,var(--color-accent)_15%,transparent)_0%,transparent_70%)]"
/>
{/* Radiating atmospheric rays */}
<svg
className="absolute top-0 left-1/2 -translate-x-1/2 w-[1200px] h-[600px] opacity-40 mix-blend-multiply"
viewBox="0 0 1200 600"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<defs>
<linearGradient id="rayGradient" x1="600" y1="0" x2="600" y2="600" gradientUnits="userSpaceOnUse">
<stop stopColor={color} stopOpacity="0.3" />
<stop offset="0.5" stopColor={color} stopOpacity="0.1" />
<stop offset="1" stopColor={color} stopOpacity="0" />
</linearGradient>
</defs>
{/* Fan of light beams */}
<polygon points="600,0 150,600 240,600" fill="url(#rayGradient)" />
<polygon points="600,0 320,600 400,600" fill="url(#rayGradient)" />
<polygon points="600,0 480,600 560,600" fill="url(#rayGradient)" />
<polygon points="600,0 640,600 720,600" fill="url(#rayGradient)" />
<polygon points="600,0 800,600 880,600" fill="url(#rayGradient)" />
<polygon points="600,0 960,600 1050,600" fill="url(#rayGradient)" />
</svg>
</div>
);
}
+225
View File
@@ -0,0 +1,225 @@
'use client';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils';
interface MorphingTextProps {
className?: string;
texts: string[];
morphTime?: number;
cooldownTime?: number;
}
const SvgFilters: React.FC = () => (
<svg
id="magicui-morphing-filters"
className="fixed h-0 w-0 pointer-events-none"
aria-hidden="true"
preserveAspectRatio="xMidYMid slice"
>
<defs>
<filter id="magicui-threshold">
<feColorMatrix
in="SourceGraphic"
type="matrix"
values="1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 255 -140"
/>
</filter>
</defs>
</svg>
);
/**
* Magic UI - Morphing Text (Thermal-Optimized)
* Fluid text morphing using blur & threshold filter with zero offscreen CPU consumption.
* Pauses RAF when resting and when scrolled out of view.
* Reference: https://magicui.design/docs/components/morphing-text
*/
export function MorphingText({
texts,
className,
morphTime = 1.2,
cooldownTime = 2.2,
}: MorphingTextProps) {
const containerRef = useRef<HTMLDivElement>(null);
const text1Ref = useRef<HTMLSpanElement>(null);
const text2Ref = useRef<HTMLSpanElement>(null);
const textIndexRef = useRef(0);
const morphRef = useRef(0);
const cooldownRef = useRef(0);
const timeRef = useRef(new Date());
const [isInView, setIsInView] = useState(false);
// Set text blur & opacity styles during the morphing phase
const setStyles = useCallback(
(fraction: number) => {
const current1 = text1Ref.current;
const current2 = text2Ref.current;
if (!current1 || !current2) return;
// Blur calculation: clamped so small fonts retain high legibility
const blurVal = Math.min(8 / fraction - 8, 24);
current2.style.filter = `blur(${blurVal}px)`;
current2.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;
const invertedFraction = 1 - fraction;
const blurInv = Math.min(8 / invertedFraction - 8, 24);
current1.style.filter = `blur(${blurInv}px)`;
current1.style.opacity = `${Math.pow(invertedFraction, 0.4) * 100}%`;
current1.textContent = texts[textIndexRef.current % texts.length];
current2.textContent = texts[(textIndexRef.current + 1) % texts.length];
},
[texts]
);
const doMorph = useCallback(() => {
morphRef.current -= cooldownRef.current;
cooldownRef.current = 0;
let fraction = morphRef.current / morphTime;
if (fraction > 1) {
cooldownRef.current = cooldownTime;
fraction = 1;
}
setStyles(fraction);
if (fraction === 1) {
textIndexRef.current++;
}
}, [setStyles, morphTime, cooldownTime]);
const doCooldown = useCallback(() => {
morphRef.current = 0;
const current1 = text1Ref.current;
const current2 = text2Ref.current;
if (current1 && current2) {
current2.style.filter = 'none';
current2.style.opacity = '100%';
current1.style.filter = 'none';
current1.style.opacity = '0%';
}
}, []);
// IntersectionObserver: 0% CPU consumption when scrolled out of view
useEffect(() => {
const el = containerRef.current;
if (!el || typeof IntersectionObserver === 'undefined') {
setIsInView(true);
return;
}
const observer = new IntersectionObserver(
([entry]) => {
setIsInView(entry.isIntersecting);
},
{ threshold: 0.1 }
);
observer.observe(el);
return () => observer.disconnect();
}, []);
// Main animation driver: runs only while in view and page visible
useEffect(() => {
if (!isInView || !texts || texts.length === 0) return;
let animationFrameId: number | null = null;
let cooldownTimeoutId: NodeJS.Timeout | null = null;
let isRunning = true;
timeRef.current = new Date();
const step = () => {
if (!isRunning || document.hidden) return;
const newTime = new Date();
const dt = (newTime.getTime() - timeRef.current.getTime()) / 1000;
timeRef.current = newTime;
cooldownRef.current -= dt;
if (cooldownRef.current <= 0) {
// Active morph phase: run RAF smoothly
doMorph();
animationFrameId = requestAnimationFrame(step);
} else {
// Resting phase: apply clean cooldown state and pause RAF!
doCooldown();
// Rather than spinning 120 RAF loops per second doing nothing, schedule timer
const waitMs = Math.max(50, cooldownRef.current * 1000);
cooldownTimeoutId = setTimeout(() => {
cooldownRef.current = 0;
timeRef.current = new Date();
animationFrameId = requestAnimationFrame(step);
}, waitMs);
}
};
animationFrameId = requestAnimationFrame(step);
const handleVisibilityChange = () => {
if (document.hidden) {
if (animationFrameId) cancelAnimationFrame(animationFrameId);
if (cooldownTimeoutId) clearTimeout(cooldownTimeoutId);
} else {
timeRef.current = new Date();
animationFrameId = requestAnimationFrame(step);
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
isRunning = false;
if (animationFrameId) cancelAnimationFrame(animationFrameId);
if (cooldownTimeoutId) clearTimeout(cooldownTimeoutId);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [isInView, texts, doMorph, doCooldown]);
const [useSvgThreshold, setUseSvgThreshold] = useState(false);
useEffect(() => {
// Only apply SVG filter on desktop non-touch browsers where SVG filters on HTML are fully supported
if (typeof window !== 'undefined') {
const isMobileOrTouch =
window.innerWidth < 1024 ||
navigator.maxTouchPoints > 0 ||
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
setUseSvgThreshold(!isMobileOrTouch);
}
}, []);
if (!texts || texts.length === 0) return null;
return (
<div
ref={containerRef}
style={useSvgThreshold ? { filter: 'url(#magicui-threshold) blur(0.3px)' } : undefined}
className={cn(
'relative inline-block overflow-hidden align-baseline select-none whitespace-nowrap',
className
)}
aria-label={texts[textIndexRef.current % texts.length]}
>
<span
ref={text1Ref}
className="inline-block transition-transform duration-75 whitespace-nowrap"
>
{texts[0]}
</span>
<span
ref={text2Ref}
className="absolute inset-0 m-auto inline-block text-left opacity-0 whitespace-nowrap"
/>
{useSvgThreshold && <SvgFilters />}
</div>
);
}
+70
View File
@@ -0,0 +1,70 @@
'use client';
import React from 'react';
import { cn } from '@/lib/utils';
interface RainbowButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
href?: string;
}
/**
* Magic UI - Rainbow Button
* Vibrant animated chromatic gradient border button with high contrast and smooth tap feedback.
* Uses CSS mask border technique with explicit border-radius: 9999px for 100% perfect pill curvature on all devices.
* Reference: https://magicui.design/docs/components/rainbow-button
*/
export const RainbowButton = React.forwardRef<
HTMLButtonElement,
RainbowButtonProps
>(({ children, href, className, ...props }, ref) => {
const content = (
<>
{/* Chromatic Border Ring: active on hover, 0% CPU at rest */}
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 p-[2px] transition-opacity duration-300 group-hover:opacity-100"
style={{
borderRadius: 9999,
background: 'linear-gradient(90deg, #3b82f6, #6366f1, #ec4899, #f59e0b, #10b981, #3b82f6)',
backgroundSize: '200% 100%',
WebkitMask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
WebkitMaskComposite: 'xor',
mask: 'linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)',
maskComposite: 'exclude',
}}
/>
{/* Inner Button Canvas */}
<span
className="relative z-10 flex h-full w-full items-center justify-center gap-2 bg-ink px-6 sm:px-7 py-3 text-paper-hi font-body text-sm sm:text-base font-bold shadow-md transition-colors duration-200 group-hover:bg-slate-900"
style={{ borderRadius: 9999 }}
>
{children}
</span>
</>
);
const baseClasses = cn(
'group relative inline-flex items-center justify-center p-[2px]',
'cursor-pointer select-none text-center outline-none',
'focus-visible:ring-2 focus-visible:ring-accent active:scale-[0.98]',
'disabled:opacity-50 disabled:pointer-events-none transition-transform duration-150',
className
);
if (href) {
return (
<a href={href} className={baseClasses} style={{ borderRadius: 9999 }}>
{content}
</a>
);
}
return (
<button ref={ref} className={baseClasses} style={{ borderRadius: 9999 }} {...props}>
{content}
</button>
);
});
RainbowButton.displayName = 'RainbowButton';
+116 -261
View File
@@ -1,292 +1,147 @@
'use client';
import React, { useEffect, useRef, useState } from 'react';
import React, { useEffect, useState } from 'react';
import { motion, useSpring, useMotionValue } from 'framer-motion';
export interface SpringConfig {
damping: number;
stiffness: number;
mass: number;
restDelta: number;
}
interface SmoothCursorProps {
cursor?: React.ReactNode;
springConfig?: SpringConfig;
}
const defaultSpringConfig: SpringConfig = {
damping: 40,
stiffness: 420,
mass: 0.85,
restDelta: 0.001,
};
/**
* LiquidGlassLensCursor:
* Pure Optical Liquid Glass Lens cursor with 100% transparent crystal body,
* sharp specular water-drop glints, dynamic velocity squash & stretch.
*
* Exclusively active on Desktop & Laptop computers with precise mouse / trackpad pointers.
* Completely disabled and removed on Phones, Tablets, and Touchscreen devices.
* Magic UI Arrow SVG aligned exactly to the click tip (0, 0)
*/
export function SmoothCursor() {
const [isEnabled, setIsEnabled] = useState(false);
const lensRef = useRef<HTMLDivElement>(null);
const dotRef = useRef<HTMLDivElement>(null);
const causticRef = useRef<HTMLDivElement>(null);
const DefaultCursorSVG = () => (
<svg
className="relative h-6 w-6 -translate-x-[5.5px] -translate-y-[3.2px] select-none pointer-events-none drop-shadow-md"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
d="M5.5 3.214V20.5l4.636-4.636 4.364 8.636 2.5-1.25-4.364-8.636H20.5L5.5 3.214z"
fill="currentColor"
className="text-stone-900"
/>
</svg>
);
/**
* Magic UI - Smooth Cursor
* Physics-based custom cursor with fluid spring movement.
* Completely disables on mobile and touch devices to save 100% CPU.
* Uses RAF throttling on desktop to avoid CPU heating.
* Reference: https://magicui.design/docs/components/smooth-cursor
*/
export function SmoothCursor({
cursor = <DefaultCursorSVG />,
springConfig = defaultSpringConfig,
}: SmoothCursorProps) {
const [isTouchDevice, setIsTouchDevice] = useState(true); // default true for SSR & safety
const [hasMoved, setHasMoved] = useState(false);
const [isPointer, setIsPointer] = useState(false);
const [isClicking, setIsClicking] = useState(false);
const cursorX = useMotionValue(-100);
const cursorY = useMotionValue(-100);
const smoothX = useSpring(cursorX, springConfig);
const smoothY = useSpring(cursorY, springConfig);
useEffect(() => {
// Detect mobile touch devices or low-capability screens
if (typeof window === 'undefined') return;
// Detect phones, tablets, or touchscreen devices (zero touch overhead)
const isMobileOrTablet =
const isTouch =
window.innerWidth < 1024 ||
navigator.maxTouchPoints > 0 ||
'ontouchstart' in window ||
window.innerWidth < 1024 ||
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Tablet/i.test(navigator.userAgent) ||
(window.matchMedia && window.matchMedia('(pointer: coarse)').matches) ||
(window.matchMedia && !window.matchMedia('(hover: hover)').matches);
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const hasFinePointer =
window.matchMedia && window.matchMedia('(hover: hover) and (pointer: fine)').matches;
// Completely disable and remove on phones and tablets
if (isMobileOrTablet || !hasFinePointer) {
if (isTouch) {
setIsTouchDevice(true);
document.documentElement.classList.remove('custom-cursor-active');
return;
}
setIsEnabled(true);
}, []);
setIsTouchDevice(false);
document.documentElement.classList.add('custom-cursor-active');
useEffect(() => {
if (!isEnabled) return;
let rafId: number | null = null;
const lens = lensRef.current;
const dot = dotRef.current;
const caustic = causticRef.current;
if (!lens || !dot) return;
const handleMouseMove = (e: MouseEvent) => {
const clientX = e.clientX;
const clientY = e.clientY;
const target = e.target as HTMLElement | null;
let mouseX = -200;
let mouseY = -200;
let prevMouseX = -200;
let prevMouseY = -200;
let lensX = -200;
let lensY = -200;
let causticX = -200;
let causticY = -200;
let currentSpeed = 0;
let isHovered = false;
let isPressed = false;
let isVisible = false;
let animId = 0;
// Start RAF loop only when needed
const startLoop = () => {
if (!animId && isVisible && !document.hidden) {
animId = requestAnimationFrame(loop);
if (!rafId) {
rafId = requestAnimationFrame(() => {
cursorX.set(clientX);
cursorY.set(clientY);
if (!hasMoved) setHasMoved(true);
if (target && typeof target.closest === 'function') {
setIsPointer(!!target.closest('a, button, [role="button"], [role="slider"], input, select, textarea, label'));
}
rafId = null;
});
}
};
// Desktop Mouse & Pointer Movement
const onMouseMove = (e: MouseEvent) => {
mouseX = e.clientX;
mouseY = e.clientY;
const handleMouseDown = () => setIsClicking(true);
const handleMouseUp = () => setIsClicking(false);
if (!isVisible) {
isVisible = true;
lens.style.opacity = '1';
dot.style.opacity = '1';
if (caustic) caustic.style.opacity = '1';
}
startLoop();
};
const onMouseLeave = () => {
isVisible = false;
lens.style.opacity = '0';
dot.style.opacity = '0';
if (caustic) caustic.style.opacity = '0';
if (animId) {
cancelAnimationFrame(animId);
animId = 0;
}
};
const onMouseEnter = () => {
isVisible = true;
lens.style.opacity = '1';
dot.style.opacity = '1';
if (caustic) caustic.style.opacity = '1';
startLoop();
};
const onMouseDown = () => {
isPressed = true;
startLoop();
};
const onMouseUp = () => {
isPressed = false;
startLoop();
};
// Throttled interactive element detection for magnetic lens scaling
let lastCheck = 0;
const onMouseOver = (e: MouseEvent) => {
const now = performance.now();
if (now - lastCheck < 25) return;
lastCheck = now;
const target = e.target as Node | null;
if (!target) return;
const element = (target instanceof Element ? target : target.parentElement) as HTMLElement | null;
if (!element || typeof element.closest !== 'function') return;
const interactive = element.closest('a, button, input, textarea, select, [role="button"], .cursor-pointer, [data-interactive]');
const wasHovered = isHovered;
isHovered = !!interactive;
if (wasHovered !== isHovered) {
startLoop();
}
};
// High performance RAF loop (sleeps when cursor is idle, wakes on movement)
const loop = () => {
if (document.hidden || !isVisible) {
animId = 0;
return;
}
const vx = mouseX - prevMouseX;
const vy = mouseY - prevMouseY;
prevMouseX = mouseX;
prevMouseY = mouseY;
const rawSpeed = Math.hypot(vx, vy);
currentSpeed += (rawSpeed - currentSpeed) * 0.2;
// Silky liquid lag for pure organic fluid following
lensX += (mouseX - lensX) * 0.35;
lensY += (mouseY - lensY) * 0.35;
// Secondary ambient caustic trailing slightly behind
if (caustic) {
causticX += (mouseX - causticX) * 0.18;
causticY += (mouseY - causticY) * 0.18;
caustic.style.transform = `translate3d(${causticX}px, ${causticY}px, 0) translate3d(-50%, -50%, 0)`;
}
// Dynamic liquid squash & stretch based on velocity and direction
const angle = Math.atan2(vy, vx);
const stretch = Math.min(currentSpeed * 0.0035, 0.32); // Max stretch 32%
const baseScale = isPressed ? (isHovered ? 1.35 : 0.9) : (isHovered ? 1.55 : 1.0);
const scaleX = baseScale * (1 + stretch);
const scaleY = baseScale * (1 - stretch * 0.5);
// Hardware accelerated transform with velocity alignment
if (stretch > 0.02) {
lens.style.transform = `translate3d(${lensX}px, ${lensY}px, 0) translate3d(-50%, -50%, 0) rotate(${angle}rad) scale(${scaleX}, ${scaleY}) rotate(${-angle}rad)`;
} else {
lens.style.transform = `translate3d(${lensX}px, ${lensY}px, 0) translate3d(-50%, -50%, 0) scale(${baseScale})`;
}
// Precision pinpoint dot
const dotScale = isHovered ? 0 : (isPressed ? 0.7 : 1);
dot.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0) translate3d(-50%, -50%, 0) scale(${dotScale})`;
// Idle sleep check: if mouse stopped moving and lens reached position, pause RAF loop!
const dist = Math.hypot(mouseX - lensX, mouseY - lensY);
if (dist < 0.1 && currentSpeed < 0.02) {
lensX = mouseX;
lensY = mouseY;
lens.style.transform = `translate3d(${lensX}px, ${lensY}px, 0) translate3d(-50%, -50%, 0) scale(${baseScale})`;
animId = 0;
return;
}
animId = requestAnimationFrame(loop);
};
const onVisibilityChange = () => {
if (document.hidden) {
if (animId) {
cancelAnimationFrame(animId);
animId = 0;
}
} else if (isVisible) {
startLoop();
}
};
window.addEventListener('mousemove', onMouseMove, { passive: true });
window.addEventListener('mouseleave', onMouseLeave);
window.addEventListener('mouseenter', onMouseEnter);
window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mouseup', onMouseUp);
document.addEventListener('mouseover', onMouseOver, { passive: true });
document.addEventListener('visibilitychange', onVisibilityChange);
startLoop();
window.addEventListener('mousemove', handleMouseMove, { passive: true });
window.addEventListener('mousedown', handleMouseDown, { passive: true });
window.addEventListener('mouseup', handleMouseUp, { passive: true });
return () => {
if (animId) cancelAnimationFrame(animId);
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseleave', onMouseLeave);
window.removeEventListener('mouseenter', onMouseEnter);
window.removeEventListener('mousedown', onMouseDown);
window.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('mouseover', onMouseOver);
document.removeEventListener('visibilitychange', onVisibilityChange);
if (rafId) cancelAnimationFrame(rafId);
document.documentElement.classList.remove('custom-cursor-active');
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mousedown', handleMouseDown);
window.removeEventListener('mouseup', handleMouseUp);
};
}, [isEnabled]);
}, [cursorX, cursorY, hasMoved]);
// Completely removed on phones and tablets
if (!isEnabled) {
return null;
}
if (isTouchDevice) return null;
return (
<div className="pointer-events-none fixed inset-0 z-[99999] overflow-hidden select-none hidden md:block">
{/* 1. Ambient Caustic Aura (Fluid blue light dispersion) */}
<div
ref={causticRef}
className="fixed top-0 left-0 w-24 h-24 rounded-full pointer-events-none opacity-0 transition-opacity duration-300 will-change-transform transform-gpu [backface-visibility:hidden]"
style={{
background: 'radial-gradient(circle, rgba(56, 189, 248, 0.12) 0%, rgba(99, 102, 241, 0.05) 50%, transparent 70%)',
filter: 'blur(10px)',
}}
/>
{/* 2. Pure Liquid Glass Lens (100% Crystal Transparent Body, Sharp Specular Glints, Zero Frosting) */}
<div
ref={lensRef}
className="fixed top-0 left-0 w-12 h-12 rounded-full pointer-events-none opacity-0 will-change-transform transform-gpu [backface-visibility:hidden] transition-opacity duration-200"
style={{
// Optical clear glass: ZERO blur (eliminates all frosted haze) + optical contrast & saturation pop
backdropFilter: 'contrast(1.16) brightness(1.05) saturate(1.28)',
WebkitBackdropFilter: 'contrast(1.16) brightness(1.05) saturate(1.28)',
// Ultra-sheer crystal body: 98% transparent center, subtle sapphire meniscus tint at the outer rim
background:
'radial-gradient(circle at 40% 35%, rgba(255, 255, 255, 0.12) 0%, rgba(255, 255, 255, 0.02) 40%, rgba(37, 99, 235, 0.04) 75%, rgba(37, 99, 235, 0.12) 100%)',
// Sharp liquid meniscus rim & caustic reflection
boxShadow:
'0 4px 20px -2px rgba(37, 99, 235, 0.22), 0 1px 4px rgba(15, 23, 42, 0.06), inset 0 1.5px 2px rgba(255, 255, 255, 0.85), inset 0 -1.5px 2.5px rgba(37, 99, 235, 0.35), inset 0 0 0 1px rgba(255, 255, 255, 0.45)',
border: '1px solid rgba(255, 255, 255, 0.55)',
}}
>
{/* Primary Sharp Specular Glint (Simulates sunlight reflecting off curved water droplet meniscus) */}
<div
className="absolute top-1.5 left-2 w-3.5 h-1.5 rounded-full pointer-events-none"
style={{
background: 'linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(255, 255, 255, 0.4) 60%, transparent 100%)',
transform: 'rotate(-25deg)',
}}
/>
{/* Pinpoint Micro-Glint (Sharp point-light reflection) */}
<div
className="absolute top-1 left-2.5 w-1 h-1 rounded-full bg-white pointer-events-none shadow-[0_0_2px_rgba(255,255,255,0.95)]"
/>
{/* Secondary Ambient Caustic Rim (Bottom-right rim reflection) */}
<div
className="absolute bottom-1 right-2 w-2.5 h-1 rounded-full pointer-events-none opacity-80"
style={{
background: 'linear-gradient(315deg, rgba(56, 189, 248, 0.7) 0%, rgba(99, 102, 241, 0.2) 100%)',
transform: 'rotate(-25deg)',
}}
/>
</div>
{/* 3. Precision Point Pip (Desktop Only, Zero Latency Pinpoint) */}
<div
ref={dotRef}
className="fixed top-0 left-0 w-1.5 h-1.5 rounded-full bg-blue-600 shadow-[0_0_8px_rgba(37,99,235,0.9)] pointer-events-none opacity-0 will-change-transform transform-gpu [backface-visibility:hidden] transition-opacity duration-150"
/>
</div>
<motion.div
className="fixed top-0 left-0 z-[999999] pointer-events-none select-none will-change-transform"
style={{
x: smoothX,
y: smoothY,
opacity: hasMoved ? 1 : 0,
}}
animate={{
scale: isClicking ? 0.88 : isPointer ? 1.2 : 1,
rotate: isPointer ? -6 : 0,
}}
transition={{
type: 'spring',
stiffness: 480,
damping: 26,
}}
>
{cursor}
</motion.div>
);
}
export default SmoothCursor;
+231
View File
@@ -0,0 +1,231 @@
'use client';
import React, {
memo,
useCallback,
useMemo,
useState,
useEffect,
type ElementType,
} from 'react';
import { useAnimate, type ValueAnimationTransition, type AnimationOptions } from 'framer-motion';
import { cn } from '@/lib/utils';
const HAS_SEGMENTER = typeof Intl !== 'undefined' && 'Segmenter' in Intl;
const splitIntoCharacters = (text: string): string[] => {
if (HAS_SEGMENTER) {
const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' });
return Array.from(segmenter.segment(text), ({ segment }) => segment);
}
return Array.from(text);
};
const extractTextFromChildren = (children: React.ReactNode): string => {
if (children == null) return '';
if (typeof children === 'string') return children;
if (typeof children === 'number') return String(children);
if (Array.isArray(children)) {
return children.map(extractTextFromChildren).join('');
}
if (React.isValidElement(children)) {
const props = children.props as Record<string, unknown>;
const childText = props.children as React.ReactNode;
if (childText != null) {
return extractTextFromChildren(childText);
}
}
return '';
};
export interface Text3DFlipProps {
children?: React.ReactNode;
words?: string[];
duration?: number;
as?: ElementType;
className?: string;
textClassName?: string;
flipTextClassName?: string;
staggerDuration?: number;
staggerFrom?: 'first' | 'last' | 'center' | number | 'random';
transition?: ValueAnimationTransition | AnimationOptions;
rotateDirection?: 'top' | 'bottom' | 'right' | 'left';
[key: string]: any;
}
/**
* Magic UI - Text 3D Flip
* Dynamic 3D perspective flip effect that rolls each letter in 3D with staggered spring physics on hover.
* Supports static text/headings as well as rotating word lists.
* Reference: https://magicui.design/docs/components/text-3d-flip
*/
export const Text3DFlip = memo(function Text3DFlip({
children,
words,
duration = 2500,
as: Component = 'span',
className,
textClassName,
flipTextClassName,
staggerDuration = 0.02,
staggerFrom = 'first',
rotateDirection = 'top',
...props
}: Text3DFlipProps) {
const [scope, animate] = useAnimate();
const [currentWordIndex, setCurrentWordIndex] = useState(0);
// Auto-cycle words if words array is provided
useEffect(() => {
if (!words || words.length <= 1) return;
const interval = setInterval(() => {
setCurrentWordIndex((prev) => (prev + 1) % words.length);
}, duration);
return () => clearInterval(interval);
}, [words, duration]);
const textContent = useMemo(() => {
if (words && words.length > 0) {
return words[currentWordIndex] || '';
}
return extractTextFromChildren(children);
}, [words, currentWordIndex, children]);
// Split by words to preserve natural text wrapping without splitting letters across lines
const tokenizedWords = useMemo(() => {
return textContent.split(' ').map((word) => ({
word,
letters: splitIntoCharacters(word),
}));
}, [textContent]);
const getStaggerDelay = useCallback(
(index: number, total: number) => {
if (typeof staggerFrom === 'number') {
return Math.abs(staggerFrom - index) * staggerDuration;
}
switch (staggerFrom) {
case 'last':
return (total - 1 - index) * staggerDuration;
case 'center': {
const center = (total - 1) / 2;
return Math.abs(center - index) * staggerDuration;
}
case 'random':
return Math.random() * total * staggerDuration;
case 'first':
default:
return index * staggerDuration;
}
},
[staggerFrom, staggerDuration]
);
const handleMouseEnter = useCallback(() => {
if (!scope.current) return;
const letterElements = scope.current.querySelectorAll('[data-letter]');
const total = letterElements.length;
const isHorizontal = rotateDirection === 'left' || rotateDirection === 'right';
letterElements.forEach((el: Element, index: number) => {
const delay = getStaggerDelay(index, total);
animate(
el,
isHorizontal
? {
rotateY: [0, 360],
z: [0, 15, 0],
color: ['inherit', 'var(--color-accent)', 'var(--color-accent)'],
}
: {
rotateX: [0, 360],
y: [0, -5, 0],
z: [0, 15, 0],
color: ['inherit', 'var(--color-accent)', 'var(--color-accent)'],
},
{
type: 'spring',
damping: 20,
stiffness: 280,
delay,
}
);
});
}, [scope, animate, getStaggerDelay, rotateDirection]);
const handleMouseLeave = useCallback(() => {
if (!scope.current) return;
const letterElements = scope.current.querySelectorAll('[data-letter]');
const total = letterElements.length;
const isHorizontal = rotateDirection === 'left' || rotateDirection === 'right';
letterElements.forEach((el: Element, index: number) => {
const delay = getStaggerDelay(index, total);
animate(
el,
isHorizontal
? {
rotateY: [360, 0],
z: 0,
color: ['var(--color-accent)', 'inherit', 'inherit'],
}
: {
rotateX: [360, 0],
y: 0,
z: 0,
color: ['var(--color-accent)', 'inherit', 'inherit'],
},
{
type: 'spring',
damping: 20,
stiffness: 280,
delay,
}
);
});
}, [scope, animate, getStaggerDelay, rotateDirection]);
return (
<Component
ref={scope}
className={cn('inline-flex flex-wrap items-center cursor-pointer select-none [perspective:1000px]', className)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
{...props}
>
<span className="inline-flex flex-wrap items-center gap-x-[0.28em]">
{tokenizedWords.map((wordObj, wordIndex) => (
<React.Fragment key={wordIndex}>
{wordIndex > 0 && <span className="inline-block select-none pointer-events-none">&nbsp;</span>}
<span className="inline-block whitespace-nowrap">
{wordObj.letters.map((letter, letterIndex) => (
<span
key={letterIndex}
data-letter
style={{
transformStyle: 'preserve-3d',
transformOrigin: '50% 50%',
backfaceVisibility: 'hidden',
WebkitBackfaceVisibility: 'hidden',
}}
className={cn(
'inline-block transform-gpu will-change-transform align-baseline transition-colors duration-150',
textClassName
)}
>
{letter}
</span>
))}
</span>
</React.Fragment>
))}
</span>
</Component>
);
});
Text3DFlip.displayName = 'Text3DFlip';
export default Text3DFlip;
+519 -154
View File
@@ -1,185 +1,550 @@
'use client';
import React, { useEffect, useState } from 'react';
import { motion, Variants } from 'framer-motion';
import { memo } from 'react';
import {
AnimatePresence,
motion,
type DOMMotionComponents,
type MotionProps,
type Variants,
} from 'framer-motion';
export type AnimationType =
import { cn } from '@/lib/utils';
export type AnimationType = 'text' | 'word' | 'character' | 'line';
export type AnimationVariant =
| 'fadeIn'
| 'blurIn'
| 'blurInUp'
| 'blurInDown'
| 'slideUp'
| 'slideDown'
| 'slideLeft'
| 'slideRight'
| 'scaleUp';
| 'scaleUp'
| 'scaleDown';
export type AnimateBy = 'character' | 'word' | 'line';
const motionElements = {
article: motion.article,
div: motion.div,
h1: motion.h1,
h2: motion.h2,
h3: motion.h3,
h4: motion.h4,
h5: motion.h5,
h6: motion.h6,
li: motion.li,
p: motion.p,
section: motion.section,
span: motion.span,
} as const;
interface TextAnimateProps {
type MotionElementType = Extract<
keyof DOMMotionComponents,
keyof typeof motionElements
>;
export interface TextAnimateProps extends Omit<MotionProps, 'children'> {
/**
* The text content to animate
*/
children: string;
/**
* The class name to be applied to the component
*/
className?: string;
/**
* The class name to be applied to each segment
*/
segmentClassName?: string;
/**
* The delay before the animation starts
*/
delay?: number;
/**
* The duration of the animation
*/
duration?: number;
/**
* Custom motion variants for the animation
*/
variants?: Variants;
as?: React.ElementType;
by?: AnimateBy;
/**
* The element type to render
*/
as?: MotionElementType;
/**
* How to split the text ("text", "word", "character")
*/
by?: AnimationType;
/**
* Whether to start animation when component enters viewport
*/
startOnView?: boolean;
/**
* Whether to animate only once
*/
once?: boolean;
animation?: AnimationType;
/**
* The animation preset to use
*/
animation?: AnimationVariant;
/**
* Whether to enable accessibility features (default: true)
*/
accessible?: boolean;
}
// Ultra-smooth Apple-grade exponential easing
const easeOutApple = [0.16, 1, 0.3, 1] as const;
const staggerTimings: Record<AnimationType, number> = {
text: 0.06,
word: 0.05,
character: 0.035,
line: 0.06,
};
export function TextAnimate({
const defaultContainerVariants = {
hidden: { opacity: 1 },
show: {
opacity: 1,
transition: {
delayChildren: 0,
staggerChildren: 0.05,
},
},
visible: {
opacity: 1,
transition: {
delayChildren: 0,
staggerChildren: 0.05,
},
},
exit: {
opacity: 0,
transition: {
staggerChildren: 0.05,
staggerDirection: -1,
},
},
};
const defaultItemVariants: Variants = {
hidden: { opacity: 0 },
show: {
opacity: 1,
},
visible: {
opacity: 1,
},
exit: {
opacity: 0,
},
};
const defaultItemAnimationVariants: Record<
AnimationVariant,
{ container: Variants; item: Variants }
> = {
fadeIn: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, y: 20 },
show: {
opacity: 1,
y: 0,
transition: {
duration: 0.35,
},
},
visible: {
opacity: 1,
y: 0,
transition: {
duration: 0.35,
},
},
exit: {
opacity: 0,
y: 20,
transition: { duration: 0.3 },
},
},
},
blurIn: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, filter: 'blur(10px)' },
show: {
opacity: 1,
filter: 'blur(0px)',
transition: {
duration: 0.35,
},
},
visible: {
opacity: 1,
filter: 'blur(0px)',
transition: {
duration: 0.35,
},
},
exit: {
opacity: 0,
filter: 'blur(10px)',
transition: { duration: 0.3 },
},
},
},
blurInUp: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, filter: 'blur(10px)', y: 24 },
show: {
opacity: 1,
filter: 'none',
y: 0,
transition: {
y: { duration: 0.35, ease: [0.16, 1, 0.3, 1] },
opacity: { duration: 0.45 },
filter: { duration: 0.35 },
},
},
visible: {
opacity: 1,
filter: 'none',
y: 0,
transition: {
y: { duration: 0.35, ease: [0.16, 1, 0.3, 1] },
opacity: { duration: 0.45 },
filter: { duration: 0.35 },
},
},
exit: {
opacity: 0,
filter: 'blur(10px)',
y: 20,
transition: {
y: { duration: 0.3 },
opacity: { duration: 0.4 },
filter: { duration: 0.3 },
},
},
},
},
blurInDown: {
container: defaultContainerVariants,
item: {
hidden: { opacity: 0, filter: 'blur(10px)', y: -24 },
show: {
opacity: 1,
filter: 'none',
y: 0,
transition: {
y: { duration: 0.35, ease: [0.16, 1, 0.3, 1] },
opacity: { duration: 0.45 },
filter: { duration: 0.35 },
},
},
visible: {
opacity: 1,
filter: 'none',
y: 0,
transition: {
y: { duration: 0.35, ease: [0.16, 1, 0.3, 1] },
opacity: { duration: 0.45 },
filter: { duration: 0.35 },
},
},
},
},
slideUp: {
container: defaultContainerVariants,
item: {
hidden: { y: 20, opacity: 0 },
show: {
y: 0,
opacity: 1,
transition: {
duration: 0.35,
},
},
visible: {
y: 0,
opacity: 1,
transition: {
duration: 0.35,
},
},
exit: {
y: -20,
opacity: 0,
transition: {
duration: 0.3,
},
},
},
},
slideDown: {
container: defaultContainerVariants,
item: {
hidden: { y: -20, opacity: 0 },
show: {
y: 0,
opacity: 1,
transition: { duration: 0.35 },
},
visible: {
y: 0,
opacity: 1,
transition: { duration: 0.35 },
},
exit: {
y: 20,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
slideLeft: {
container: defaultContainerVariants,
item: {
hidden: { x: 20, opacity: 0 },
show: {
x: 0,
opacity: 1,
transition: { duration: 0.35 },
},
visible: {
x: 0,
opacity: 1,
transition: { duration: 0.35 },
},
exit: {
x: -20,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
slideRight: {
container: defaultContainerVariants,
item: {
hidden: { x: -20, opacity: 0 },
show: {
x: 0,
opacity: 1,
transition: { duration: 0.35 },
},
visible: {
x: 0,
opacity: 1,
transition: { duration: 0.35 },
},
exit: {
x: 20,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
scaleUp: {
container: defaultContainerVariants,
item: {
hidden: { scale: 0.5, opacity: 0 },
show: {
scale: 1,
opacity: 1,
transition: {
duration: 0.35,
scale: {
type: 'spring',
damping: 15,
stiffness: 300,
},
},
},
visible: {
scale: 1,
opacity: 1,
transition: {
duration: 0.35,
scale: {
type: 'spring',
damping: 15,
stiffness: 300,
},
},
},
exit: {
scale: 0.5,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
scaleDown: {
container: defaultContainerVariants,
item: {
hidden: { scale: 1.5, opacity: 0 },
show: {
scale: 1,
opacity: 1,
transition: {
duration: 0.35,
scale: {
type: 'spring',
damping: 15,
stiffness: 300,
},
},
},
visible: {
scale: 1,
opacity: 1,
transition: {
duration: 0.35,
scale: {
type: 'spring',
damping: 15,
stiffness: 300,
},
},
},
exit: {
scale: 1.5,
opacity: 0,
transition: { duration: 0.3 },
},
},
},
};
const TextAnimateBase = ({
children,
delay = 0,
duration,
className = '',
duration = 0.5,
variants,
className,
segmentClassName,
as: Component = 'span',
by = 'word',
startOnView = true,
startOnView = false,
once = true,
animation = 'slideLeft',
}: TextAnimateProps) {
if (typeof children !== 'string') {
return <Component className={className}>{children}</Component>;
by = 'character',
animation = 'blurInUp',
accessible = true,
...props
}: TextAnimateProps) => {
const MotionComponent = motionElements[Component] || motion.span;
let segments: string[] = [];
switch (by) {
case 'word':
segments = children.split(/(\s+)/);
break;
case 'character':
segments = children.split('');
break;
case 'line':
segments = children.split('\n');
break;
case 'text':
default:
segments = [children];
break;
}
// Detect mobile device to ensure ultra-smooth 60-120fps animations with zero multi-second lag
const [isMobile, setIsMobile] = useState<boolean>(false);
useEffect(() => {
if (typeof window === 'undefined') return;
const checkMobile = () => {
setIsMobile(
window.innerWidth < 768 ||
(window.matchMedia && window.matchMedia('(pointer: coarse)').matches)
);
};
checkMobile();
window.addEventListener('resize', checkMobile, { passive: true });
return () => window.removeEventListener('resize', checkMobile);
}, []);
// On phones, character-by-character animations cause CPU thrashing and take 2-3 seconds.
// Grouping into words on mobile gives instant, silky 120fps motion.
const activeBy = isMobile ? 'word' : by;
const activeDuration = duration ?? (isMobile ? 0.26 : 0.34);
const activeDelay = isMobile ? Math.min(delay * 0.4, 0.08) : delay;
const activeStagger = isMobile
? 0.018
: (activeBy === 'character' ? 0.010 : 0.03);
const offset = isMobile ? 10 : 16;
const itemVariants: Record<AnimationType, Variants> = {
fadeIn: {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { duration: activeDuration, ease: easeOutApple }
},
},
blurIn: {
hidden: { opacity: 0, filter: isMobile ? 'none' : 'blur(5px)', y: offset },
show: {
opacity: 1,
filter: 'blur(0px)',
y: 0,
transition: { duration: activeDuration, ease: easeOutApple }
},
},
slideUp: {
hidden: { y: offset, opacity: 0 },
show: {
y: 0,
opacity: 1,
transition: { duration: activeDuration, ease: easeOutApple }
},
},
slideDown: {
hidden: { y: -offset, opacity: 0 },
show: {
y: 0,
opacity: 1,
transition: { duration: activeDuration, ease: easeOutApple }
},
},
slideLeft: {
hidden: { x: offset, opacity: 0 },
show: {
x: 0,
opacity: 1,
transition: { duration: activeDuration, ease: easeOutApple }
},
},
slideRight: {
hidden: { x: -offset, opacity: 0 },
show: {
x: 0,
opacity: 1,
transition: { duration: activeDuration, ease: easeOutApple }
},
},
scaleUp: {
hidden: { scale: 0.94, opacity: 0 },
show: {
scale: 1,
opacity: 1,
transition: { duration: activeDuration, ease: easeOutApple }
},
},
};
const itemVariant = itemVariants[animation] || itemVariants.slideLeft;
const containerVariants: Variants = {
hidden: {},
show: {
transition: {
staggerChildren: activeStagger,
delayChildren: activeDelay,
},
},
};
// Split text into words. Every word is guaranteed to be in an inline-block whitespace-nowrap
// wrapper so that NO WORD EVER BREAKS MID-WORD onto two lines.
const words = children.split(/\s+/).filter(Boolean);
const finalVariants = variants
? {
container: {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
opacity: { duration: 0.01, delay },
delayChildren: delay,
staggerChildren: duration / segments.length,
},
},
visible: {
opacity: 1,
transition: {
opacity: { duration: 0.01, delay },
delayChildren: delay,
staggerChildren: duration / segments.length,
},
},
exit: {
opacity: 0,
transition: {
staggerChildren: duration / segments.length,
staggerDirection: -1,
},
},
},
item: variants,
}
: animation
? {
container: {
...defaultItemAnimationVariants[animation].container,
show: {
...defaultItemAnimationVariants[animation].container.show,
transition: {
delayChildren: delay,
staggerChildren: duration / segments.length,
},
},
visible: {
...defaultItemAnimationVariants[animation].container.show,
transition: {
delayChildren: delay,
staggerChildren: duration / segments.length,
},
},
exit: {
...defaultItemAnimationVariants[animation].container.exit,
transition: {
staggerChildren: duration / segments.length,
staggerDirection: -1,
},
},
},
item: defaultItemAnimationVariants[animation].item,
}
: { container: defaultContainerVariants, item: defaultItemVariants };
return (
<motion.span
variants={containerVariants}
initial="hidden"
whileInView={startOnView ? 'show' : undefined}
animate={!startOnView ? 'show' : undefined}
viewport={{ once, margin: '20px' }}
className={`inline ${className}`}
>
{words.map((word, wIdx) => (
<React.Fragment key={wIdx}>
<span className="inline-block whitespace-nowrap">
{activeBy === 'character' ? (
Array.from(word).map((char, cIdx) => (
<motion.span
key={`${char}-${cIdx}`}
variants={itemVariant}
className="inline-block"
>
{char}
</motion.span>
))
) : (
<motion.span
variants={itemVariant}
className="inline-block"
>
{word}
</motion.span>
<AnimatePresence mode="popLayout">
<MotionComponent
variants={finalVariants.container as Variants}
initial="hidden"
animate="show"
whileInView={startOnView ? 'show' : undefined}
viewport={{ once }}
exit="exit"
inherit={false}
className={cn('inline-block whitespace-pre-wrap', className)}
aria-label={accessible ? children : undefined}
{...props}
>
{accessible && <span className="sr-only">{children}</span>}
{segments.map((segment, i) => (
<motion.span
key={`${by}-${segment}-${i}`}
variants={finalVariants.item}
custom={i * staggerTimings[by]}
className={cn(
by === 'line' ? 'block' : 'inline-block whitespace-pre overflow-visible pb-0.5',
by === 'character' && 'overflow-visible',
segmentClassName
)}
</span>
{wIdx < words.length - 1 && ' '}
</React.Fragment>
))}
</motion.span>
aria-hidden={accessible ? true : undefined}
>
{segment}
</motion.span>
))}
</MotionComponent>
</AnimatePresence>
);
}
};
export const TextAnimate = memo(TextAnimateBase);
+135
View File
@@ -0,0 +1,135 @@
'use client';
import React, { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { AuroraText } from './aurora-text';
export interface TypingAnimationProps {
children?: string;
words?: string[];
className?: string;
duration?: number;
typeSpeed?: number;
delay?: number;
showCursor?: boolean;
blinkCursor?: boolean;
cursorStyle?: 'line' | 'block' | 'underscore';
/**
* When true (default), automatically applies Magic UI AuroraText effect all the time once typing finishes.
*/
auroraAfter?: boolean;
auroraColors?: string[];
onComplete?: () => void;
}
/**
* Magic UI - Typing Animation
* Characters appearing in typed animation letter-by-letter.
* Once typing finishes, automatically transitions to Magic UI AuroraText all the time.
* Reference: https://magicui.design/docs/components/typing-animation
* Reference: https://magicui.design/docs/components/aurora-text
*/
export function TypingAnimation({
children,
words,
className,
duration = 80,
typeSpeed,
delay = 0,
showCursor = true,
blinkCursor = true,
cursorStyle = 'line',
auroraAfter = true,
auroraColors,
onComplete,
}: TypingAnimationProps) {
const targetText = useMemo(
() => (words && words[0]) || children || '',
[words, children]
);
const [displayedText, setDisplayedText] = useState<string>('');
const [isCompleted, setIsCompleted] = useState(false);
const onCompleteRef = useRef(onComplete);
onCompleteRef.current = onComplete;
const typingSpeed = typeSpeed ?? duration;
useEffect(() => {
let timeout: ReturnType<typeof setTimeout> | null = null;
const graphemes = Array.from(targetText);
if (graphemes.length === 0) {
setIsCompleted(true);
return;
}
let currentIndex = 0;
const startTyping = () => {
const typeNextChar = () => {
if (currentIndex < graphemes.length) {
currentIndex++;
setDisplayedText(graphemes.slice(0, currentIndex).join(''));
if (currentIndex < graphemes.length) {
timeout = setTimeout(typeNextChar, typingSpeed);
} else {
setIsCompleted(true);
onCompleteRef.current?.();
}
}
};
typeNextChar();
};
if (delay > 0) {
timeout = setTimeout(startTyping, delay);
} else {
startTyping();
}
return () => {
if (timeout !== null) clearTimeout(timeout);
};
}, [targetText, delay, typingSpeed]);
const getCursorChar = () => {
switch (cursorStyle) {
case 'block':
return '▌';
case 'underscore':
return '_';
case 'line':
default:
return '|';
}
};
// Once typing finishes, use Magic UI AuroraText all the time!
if (isCompleted && auroraAfter) {
return (
<AuroraText colors={auroraColors} className={className}>
{targetText}
</AuroraText>
);
}
return (
<span className={cn('inline-block leading-[1.08] tracking-[-0.02em]', className)}>
<span>{displayedText}</span>
{showCursor && !isCompleted && (
<span
className={cn(
'inline-block ml-0.5 text-accent font-light',
blinkCursor && 'animate-blink-cursor'
)}
>
{getCursorChar()}
</span>
)}
</span>
);
}
export default TypingAnimation;
+168
View File
@@ -0,0 +1,168 @@
'use client';
import React, { ElementType, ReactNode, useId, useRef, useEffect } from 'react';
import { cn } from '@/lib/utils';
export interface VideoTextProps {
src: string;
children: ReactNode;
as?: ElementType;
className?: string;
autoPlay?: boolean;
muted?: boolean;
loop?: boolean;
preload?: 'auto' | 'metadata' | 'none';
fontSize?: string | number;
fontWeight?: string | number;
textAnchor?: 'start' | 'middle' | 'end' | 'inherit';
dominantBaseline?: 'auto' | 'middle' | 'central' | 'hanging' | 'alphabetic' | 'inherit';
fontFamily?: string;
poster?: string;
}
/**
* Magic UI - Video Text
* Dynamic typography component with looping video playing masked inside the text.
* Optimized with IntersectionObserver to completely halt video decoding when scrolled offscreen.
* Reference: https://magicui.design/docs/components/video-text
*/
export function VideoText({
src,
children,
as: Component = 'div',
className,
autoPlay = true,
muted = true,
loop = true,
preload = 'auto',
fontSize = 106,
fontWeight = 900,
textAnchor = 'start',
dominantBaseline = 'central',
fontFamily = 'var(--font-display), var(--font-poppins), system-ui, sans-serif',
poster,
}: VideoTextProps) {
const rawId = useId();
const videoRef = useRef<HTMLVideoElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const clipId = `video-text-clip-${rawId.replace(/:/g, '')}`;
// Pause video decoding when offscreen to completely eliminate CPU/GPU drain
useEffect(() => {
const video = videoRef.current;
const container = containerRef.current;
if (!video || !container) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting && !document.hidden) {
video.play().catch(() => {});
} else {
video.pause();
}
},
{ threshold: 0.05 }
);
observer.observe(container);
return () => {
observer.disconnect();
video.pause();
};
}, []);
// Parse lines if children is a multiline string or array
const textLines = React.useMemo(() => {
if (typeof children === 'string') {
return children.split('\n').map((l) => l.trim()).filter(Boolean);
}
if (Array.isArray(children)) {
return children.filter(Boolean);
}
return [children];
}, [children]);
const isMultiLine = textLines.length > 1;
const singleLineStr = typeof children === 'string' ? children : textLines[0] ? String(textLines[0]) : '';
const charCount = Math.max(singleLineStr.length, 6);
// Wide optical letter geometry so the water video has rich surface visibility
const autoWidth = Math.round(charCount * 68) + 24;
const viewBoxWidth = isMultiLine ? 1000 : autoWidth;
const viewBoxHeight = isMultiLine ? 140 * textLines.length : 126;
const posX = textAnchor === 'start' ? '0.5%' : textAnchor === 'end' ? '99.5%' : '50%';
return (
<Component
ref={containerRef as any}
className={cn('relative w-full overflow-hidden flex items-center select-none', className)}
>
<svg
className="w-full h-full pointer-events-none"
viewBox={`0 0 ${viewBoxWidth} ${viewBoxHeight}`}
preserveAspectRatio="xMidYMid meet"
aria-hidden="true"
>
<defs>
<clipPath id={clipId}>
{isMultiLine ? (
<text
x={posX}
y={`${Math.round(viewBoxHeight / (textLines.length + 1))}%`}
textAnchor={textAnchor}
dominantBaseline={dominantBaseline}
fontSize={fontSize}
fontWeight={fontWeight}
fontFamily={fontFamily}
letterSpacing="-0.02em"
>
{textLines.map((line, idx) => (
<tspan
key={idx}
x={posX}
dy={idx === 0 ? 0 : '1.15em'}
textAnchor={textAnchor}
dominantBaseline={dominantBaseline}
>
{line}
</tspan>
))}
</text>
) : (
<text
x={posX}
y="52%"
textAnchor={textAnchor}
dominantBaseline={dominantBaseline}
fontSize={fontSize}
fontWeight={fontWeight}
fontFamily={fontFamily}
letterSpacing="-0.02em"
>
{children}
</text>
)}
</clipPath>
</defs>
<foreignObject x="0" y="0" width="100%" height="100%" clipPath={`url(#${clipId})`}>
<video
ref={videoRef}
src={src}
poster={poster}
autoPlay={autoPlay}
muted={muted}
loop={loop}
playsInline
preload={preload}
className="w-full h-full object-cover"
/>
</foreignObject>
</svg>
{/* Accessible fallback text for screen readers */}
<span className="sr-only">{singleLineStr || 'Imagine Transform'}</span>
</Component>
);
}
export default VideoText;