"use client"; import { useEffect, useId, useLayoutEffect, useRef } from 'react'; import './ElectricBorder.css'; const ElectricBorder = ({ children, color = '#5227FF', speed = 1, chaos = 1, thickness = 2, className, style }) => { const rawId = useId().replace(/[:]/g, ''); const filterId = `turbulent-displace-${rawId}`; const svgRef = useRef(null); const rootRef = useRef(null); const strokeRef = useRef(null); const updateAnim = () => { const svg = svgRef.current; const host = rootRef.current; if (!svg || !host) return; if (strokeRef.current) { strokeRef.current.style.filter = `url(#${filterId})`; } const width = Math.max(1, Math.round(host.clientWidth || host.getBoundingClientRect().width || 0)); const height = Math.max(1, Math.round(host.clientHeight || host.getBoundingClientRect().height || 0)); const dyAnims = Array.from(svg.querySelectorAll('feOffset > animate[attributeName="dy"]')); if (dyAnims.length >= 2) { dyAnims[0].setAttribute('values', `${height}; 0`); dyAnims[1].setAttribute('values', `0; -${height}`); } const dxAnims = Array.from(svg.querySelectorAll('feOffset > animate[attributeName="dx"]')); if (dxAnims.length >= 2) { dxAnims[0].setAttribute('values', `${width}; 0`); dxAnims[1].setAttribute('values', `0; -${width}`); } const baseDur = 6; const dur = Math.max(0.001, baseDur / (speed || 1)); [...dyAnims, ...dxAnims].forEach(a => a.setAttribute('dur', `${dur}s`)); const disp = svg.querySelector('feDisplacementMap'); if (disp) disp.setAttribute('scale', String(30 * (chaos || 1))); const filterEl = svg.querySelector(`#${CSS.escape(filterId)}`); if (filterEl) { filterEl.setAttribute('x', '-200%'); filterEl.setAttribute('y', '-200%'); filterEl.setAttribute('width', '500%'); filterEl.setAttribute('height', '500%'); } requestAnimationFrame(() => { [...dyAnims, ...dxAnims].forEach(a => { if (typeof a.beginElement === 'function') { try { a.beginElement(); } catch { console.warn('ElectricBorder: beginElement failed, this may be due to a browser limitation.'); } } }); }); }; useEffect(() => { updateAnim(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [speed, chaos]); useLayoutEffect(() => { if (!rootRef.current) return; const ro = new ResizeObserver(() => updateAnim()); ro.observe(rootRef.current); updateAnim(); return () => ro.disconnect(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const vars = { ['--electric-border-color']: color, ['--eb-border-width']: `${thickness}px` }; return (
{children}
); }; export default ElectricBorder;