A moving-border component from Aceternity UI.
From Aceternity UI
1"use client";
2import React from "react";
3import {
4 motion,
5 useAnimationFrame,
6 useMotionTemplate,
7 useMotionValue,
8 useTransform,
9} from "motion/react";
10import { useRef } from "react";
11import { cn } from "@/lib/utils";
12
13export function Button({
14 borderRadius = "1.75rem",
15 children,
16 as: Component = "button",
17 containerClassName,
18 borderClassName,
19 duration,
20 className,
21 ...otherProps
22}: {
23 borderRadius?: string;
24 children: React.ReactNode;
25 as?: any;
26 containerClassName?: string;
27 borderClassName?: string;
28 duration?: number;
29 className?: string;
30 [key: string]: any;
31}) {
32 return (
33 <Component
34 className={cn(
35 "relative h-16 w-40 overflow-hidden bg-transparent p-[1px] text-xl",
36 containerClassName,
37 )}
38 style={{
39 borderRadius: borderRadius,
40 }}
41 {...otherProps}
42 >
43 <div
44 className="absolute inset-0"
45 style={{ borderRadius: `calc(${borderRadius} * 0.96)` }}
46 >
47 <MovingBorder duration={duration} rx="30%" ry="30%">
48 <div
49 className={cn(
50 "h-20 w-20 bg-[radial-gradient(#0ea5e9_40%,transparent_60%)] opacity-[0.8]",
51 borderClassName,
52 )}
53 />
54 </MovingBorder>
55 </div>
56
57 <div
58 className={cn(
59 "relative flex h-full w-full items-center justify-center border border-slate-800 bg-slate-900/[0.8] text-sm text-white antialiased backdrop-blur-xl",
60 className,
61 )}
62 style={{
63 borderRadius: `calc(${borderRadius} * 0.96)`,
64 }}
65 >
66 {children}
67 </div>
68 </Component>
69 );
70}
71
72export const MovingBorder = ({
73 children,
74 duration = 3000,
75 rx,
76 ry,
77 ...otherProps
78}: {
79 children: React.ReactNode;
80 duration?: number;
81 rx?: string;
82 ry?: string;
83 [key: string]: any;
84}) => {
85 const pathRef = useRef<any>();
86 const progress = useMotionValue<number>(0);
87
88 useAnimationFrame((time) => {
89 const length = pathRef.current?.getTotalLength();
90 if (length) {
91 const pxPerMillisecond = length / duration;
92 progress.set((time * pxPerMillisecond) % length);
93 }
94 });
95
96 const x = useTransform(
97 progress,
98 (val) => pathRef.current?.getPointAtLength(val).x,
99 );
100 const y = useTransform(
101 progress,
102 (val) => pathRef.current?.getPointAtLength(val).y,
103 );
104
105 const transform = useMotionTemplate`translateX(${x}px) translateY(${y}px) translateX(-50%) translateY(-50%)`;
106
107 return (
108 <>
109 <svg
110 xmlns="http://www.w3.org/2000/svg"
111 preserveAspectRatio="none"
112 className="absolute h-full w-full"
113 width="100%"
114 height="100%"
115 {...otherProps}
116 >
117 <rect
118 fill="none"
119 width="100%"
120 height="100%"
121 rx={rx}
122 ry={ry}
123 ref={pathRef}
124 />
125 </svg>
126 <motion.div
127 style={{
128 position: "absolute",
129 top: 0,
130 left: 0,
131 display: "inline-block",
132 transform,
133 }}
134 >
135 {children}
136 </motion.div>
137 </>
138 );
139};
140