Files
webb/src/components/magicui/border-beam.tsx
T

110 lines
3.1 KiB
TypeScript
Raw Normal View History

'use client';
import React, { useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils';
interface BorderBeamProps {
className?: string;
size?: number;
duration?: number;
borderWidth?: number;
anchor?: number;
colorFrom?: string;
colorTo?: string;
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 = '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`,
'--duration': `${duration}s`,
'--anchor': `${anchor}%`,
'--border-width': `${borderWidth}px`,
'--color-from': colorFrom,
'--color-to': colorTo,
'--delay': `-${delay}s`,
} as React.CSSProperties
}
className={cn(
'pointer-events-none absolute inset-0 rounded-[inherit] overflow-hidden motion-reduce:hidden',
className
)}
>
<div
className="absolute inset-0 rounded-[inherit]"
style={{
padding: `${borderWidth}px`,
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={cn(
'absolute inset-[-100%] pointer-events-none',
isVisible && !isTouchDevice && 'animate-spin'
)}
style={{
animationDuration: `${duration}s`,
animationDelay: `${delay}s`,
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;