import React, { useState, useEffect } from "react"; const SearchBar = ({ onSearch }) => { const [query, setQuery] = useState(""); const [placeholderIndex, setPlaceholderIndex] = useState(0); const [placeholder, setPlaceholder] = useState(""); const [showInitialPlaceholder, setShowInitialPlaceholder] = useState(true); const initialPlaceholder = "Discover thousands of spaces"; const placeholders = [ "Generate music", "Remove background from images", "Translate text", "Chat with a PDF file", "Generate anime images", "Recognize objects in images", "Perform sentiment analysis", "Help me pick a laptop", "Face recognition", "Drawing canvas", "Create 3D objects from images", "Play a text-based game", "Predict stock prices", "Recommend movies", "Image classification", "Summarize text", "Generate video from text and audio", "Help me organize a trip", "Write a children's story", "Chat with a cat", ]; useEffect(() => { const initialTimeout = setTimeout(() => { setShowInitialPlaceholder(false); }, 4000); return () => clearTimeout(initialTimeout); }, []); useEffect(() => { if (!showInitialPlaceholder && query === "") { let typingInterval; if (placeholder.length < placeholders[placeholderIndex].length) { const typingSpeed = Math.floor(Math.random() * 50) + 100; typingInterval = setInterval(() => { setPlaceholder(prevPlaceholder => prevPlaceholder + placeholders[placeholderIndex][placeholder.length]); }, typingSpeed); } return () => clearInterval(typingInterval); } }, [placeholder, placeholderIndex, showInitialPlaceholder, query]); useEffect(() => { if (!showInitialPlaceholder && query === "") { const indexInterval = setInterval(() => { if (placeholder === placeholders[placeholderIndex]) { setPlaceholderIndex(Math.floor(Math.random() * placeholders.length)); setPlaceholder(""); // reset the placeholder when the index changes } }, 1500); return () => clearInterval(indexInterval); } }, [placeholder, placeholderIndex, showInitialPlaceholder, query]); const handleKeyDown = (event) => { if (event.key === "Enter") { onSearch(query); } }; const handleChange = (e) => { setQuery(e.target.value); if (e.target.value === "") { setPlaceholder(""); setPlaceholderIndex(Math.floor(Math.random() * placeholders.length)); } }; return (
); }; export default SearchBar;