A placeholders-and-vanish-input component from Aceternity UI.
From Aceternity UI
1"use client";
2
3import { AnimatePresence, motion } from "motion/react";
4import { useCallback, useEffect, useRef, useState } from "react";
5import { cn } from "@/lib/utils";
6
7export function PlaceholdersAndVanishInput({
8 placeholders,
9 onChange,
10 onSubmit,
11}: {
12 placeholders: string[];
13 onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
14 onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
15}) {
16 const [currentPlaceholder, setCurrentPlaceholder] = useState(0);
17
18 const intervalRef = useRef<NodeJS.Timeout | null>(null);
19 const startAnimation = () => {
20 intervalRef.current = setInterval(() => {
21 setCurrentPlaceholder((prev) => (prev + 1) % placeholders.length);
22 }, 3000);
23 };
24 const handleVisibilityChange = () => {
25 if (document.visibilityState !== "visible" && intervalRef.current) {
26 clearInterval(intervalRef.current); // Clear the interval when the tab is not visible
27 intervalRef.current = null;
28 } else if (document.visibilityState === "visible") {
29 startAnimation(); // Restart the interval when the tab becomes visible
30 }
31 };
32
33 useEffect(() => {
34 startAnimation();
35 document.addEventListener("visibilitychange", handleVisibilityChange);
36
37 return () => {
38 if (intervalRef.current) {
39 clearInterval(intervalRef.current);
40 }
41 document.removeEventListener("visibilitychange", handleVisibilityChange);
42 };
43 }, [placeholders]);
44
45 const canvasRef = useRef<HTMLCanvasElement>(null);
46 const newDataRef = useRef<any[]>([]);
47 const inputRef = useRef<HTMLInputElement>(null);
48 const [value, setValue] = useState("");
49 const [animating, setAnimating] = useState(false);
50
51 const draw = useCallback(() => {
52 if (!inputRef.current) return;
53 const canvas = canvasRef.current;
54 if (!canvas) return;
55 const ctx = canvas.getContext("2d");
56 if (!ctx) return;
57
58 canvas.width = 800;
59 canvas.height = 800;
60 ctx.clearRect(0, 0, 800, 800);
61 const computedStyles = getComputedStyle(inputRef.current);
62
63 const fontSize = parseFloat(computedStyles.getPropertyValue("font-size"));
64 ctx.font = `${fontSize * 2}px ${computedStyles.fontFamily}`;
65 ctx.fillStyle = "#FFF";
66 ctx.fillText(value, 16, 40);
67
68 const imageData = ctx.getImageData(0, 0, 800, 800);
69 const pixelData = imageData.data;
70 const newData: any[] = [];
71
72 for (let t = 0; t < 800; t++) {
73 let i = 4 * t * 800;
74 for (let n = 0; n < 800; n++) {
75 let e = i + 4 * n;
76 if (
77 pixelData[e] !== 0 &&
78 pixelData[e + 1] !== 0 &&
79 pixelData[e + 2] !== 0
80 ) {
81 newData.push({
82 x: n,
83 y: t,
84 color: [
85 pixelData[e],
86 pixelData[e + 1],
87 pixelData[e + 2],
88 pixelData[e + 3],
89 ],
90 });
91 }
92 }
93 }
94
95 newDataRef.current = newData.map(({ x, y, color }) => ({
96 x,
97 y,
98 r: 1,
99 color: `rgba(${color[0]}, ${color[1]}, ${color[2]}, ${color[3]})`,
100 }));
101 }, [value]);
102
103 useEffect(() => {
104 draw();
105 }, [value, draw]);
106
107 const animate = (start: number) => {
108 const animateFrame = (pos: number = 0) => {
109 requestAnimationFrame(() => {
110 const newArr = [];
111 for (let i = 0; i < newDataRef.current.length; i++) {
112 const current = newDataRef.current[i];
113 if (current.x < pos) {
114 newArr.push(current);
115 } else {
116 if (current.r <= 0) {
117 current.r = 0;
118 continue;
119 }
120 current.x += Math.random() > 0.5 ? 1 : -1;
121 current.y += Math.random() > 0.5 ? 1 : -1;
122 current.r -= 0.05 * Math.random();
123 newArr.push(current);
124 }
125 }
126 newDataRef.current = newArr;
127 const ctx = canvasRef.current?.getContext("2d");
128 if (ctx) {
129 ctx.clearRect(pos, 0, 800, 800);
130 newDataRef.current.forEach((t) => {
131 const { x: n, y: i, r: s, color: color } = t;
132 if (n > pos) {
133 ctx.beginPath();
134 ctx.rect(n, i, s, s);
135 ctx.fillStyle = color;
136 ctx.strokeStyle = color;
137 ctx.stroke();
138 }
139 });
140 }
141 if (newDataRef.current.length > 0) {
142 animateFrame(pos - 8);
143 } else {
144 setValue("");
145 setAnimating(false);
146 }
147 });
148 };
149 animateFrame(start);
150 };
151
152 const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
153 if (e.key === "Enter" && !animating) {
154 vanishAndSubmit();
155 }
156 };
157
158 const vanishAndSubmit = () => {
159 setAnimating(true);
160 draw();
161
162 const value = inputRef.current?.value || "";
163 if (value && inputRef.current) {
164 const maxX = newDataRef.current.reduce(
165 (prev, current) => (current.x > prev ? current.x : prev),
166 0
167 );
168 animate(maxX);
169 }
170 };
171
172 const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
173 e.preventDefault();
174 vanishAndSubmit();
175 onSubmit && onSubmit(e);
176 };
177 return (
178 <form
179 className={cn(
180 "w-full relative max-w-xl mx-auto bg-white dark:bg-zinc-800 h-12 rounded-full overflow-hidden shadow-[0px_2px_3px_-1px_rgba(0,0,0,0.1),_0px_1px_0px_0px_rgba(25,28,33,0.02),_0px_0px_0px_1px_rgba(25,28,33,0.08)] transition duration-200",
181 value && "bg-gray-50"
182 )}
183 onSubmit={handleSubmit}
184 >
185 <canvas
186 className={cn(
187 "absolute pointer-events-none text-base transform scale-50 top-[20%] left-2 sm:left-8 origin-top-left filter invert dark:invert-0 pr-20",
188 !animating ? "opacity-0" : "opacity-100"
189 )}
190 ref={canvasRef}
191 />
192 <input
193 onChange={(e) => {
194 if (!animating) {
195 setValue(e.target.value);
196 onChange && onChange(e);
197 }
198 }}
199 onKeyDown={handleKeyDown}
200 ref={inputRef}
201 value={value}
202 type="text"
203 className={cn(
204 "w-full relative text-sm sm:text-base z-50 border-none dark:text-white bg-transparent text-black h-full rounded-full focus:outline-none focus:ring-0 pl-4 sm:pl-10 pr-20",
205 animating && "text-transparent dark:text-transparent"
206 )}
207 />
208
209 <button
210 disabled={!value}
211 type="submit"
212 className="absolute right-2 top-1/2 z-50 -translate-y-1/2 h-8 w-8 rounded-full disabled:bg-gray-100 bg-black dark:bg-zinc-900 dark:disabled:bg-zinc-800 transition duration-200 flex items-center justify-center"
213 >
214 <motion.svg
215 xmlns="http://www.w3.org/2000/svg"
216 width="24"
217 height="24"
218 viewBox="0 0 24 24"
219 fill="none"
220 stroke="currentColor"
221 strokeWidth="2"
222 strokeLinecap="round"
223 strokeLinejoin="round"
224 className="text-gray-300 h-4 w-4"
225 >
226 <path stroke="none" d="M0 0h24v24H0z" fill="none" />
227 <motion.path
228 d="M5 12l14 0"
229 initial={{
230 strokeDasharray: "50%",
231 strokeDashoffset: "50%",
232 }}
233 animate={{
234 strokeDashoffset: value ? 0 : "50%",
235 }}
236 transition={{
237 duration: 0.3,
238 ease: "linear",
239 }}
240 />
241 <path d="M13 18l6 -6" />
242 <path d="M13 6l6 6" />
243 </motion.svg>
244 </button>
245
246 <div className="absolute inset-0 flex items-center rounded-full pointer-events-none">
247 <AnimatePresence mode="wait">
248 {!value && (
249 <motion.p
250 initial={{
251 y: 5,
252 opacity: 0,
253 }}
254 key={`current-placeholder-${currentPlaceholder}`}
255 animate={{
256 y: 0,
257 opacity: 1,
258 }}
259 exit={{
260 y: -15,
261 opacity: 0,
262 }}
263 transition={{
264 duration: 0.3,
265 ease: "linear",
266 }}
267 className="dark:text-zinc-500 text-sm sm:text-base font-normal text-neutral-500 pl-4 sm:pl-12 text-left w-[calc(100%-2rem)] truncate"
268 >
269 {placeholders[currentPlaceholder]}
270 </motion.p>
271 )}
272 </AnimatePresence>
273 </div>
274 </form>
275 );
276}
277