diff --git a/src/components/search.tsx b/src/components/search.tsx index 5fc0ab2..aa3c4d2 100644 --- a/src/components/search.tsx +++ b/src/components/search.tsx @@ -1,18 +1,27 @@ -import { useEffect, useState } from "react"; -import { Input, Text, Image, HStack, Box, Center, Spinner } from "@chakra-ui/react"; +import { useEffect, useRef, useState } from "react"; +import { + Input, + Text, + Image, + HStack, + Box, + Center, + Spinner, +} from "@chakra-ui/react"; import useDebounce from "@/hooks/useDebounce"; -import { SVGCardProps } from "@/interfaces/components"; +import { SearchProps, SVGCardProps } from "@/interfaces/components"; import CustomLink from "@/common/link"; import { getSvgByQuery } from "@/services"; import CustomIconBtn from "@/common/iconBtn"; import { Trash } from "phosphor-react"; import Tap from "@/animations/tap"; -const Search = () => { +const Search = ({ availableFocus = false }: SearchProps) => { const [search, setSearch] = useState(""); const [empty, setEmpty] = useState(false); const [results, setResults] = useState([]); const debouncedSearch = useDebounce(search, 500); + const searchRef = useRef(null); useEffect(() => { if (debouncedSearch) { @@ -27,6 +36,18 @@ const Search = () => { } }, [debouncedSearch]); + useEffect(() => { + const isFocusAvailable = availableFocus && searchRef.current; + + if (!isFocusAvailable) return; + + const timeoutId = setTimeout(() => { + searchRef.current?.focus(); + }, 100); + + return () => clearTimeout(timeoutId); + }, [availableFocus]); + const handleFilter = (e: React.ChangeEvent) => { setEmpty(false); setSearch(e.target.value); @@ -46,12 +67,23 @@ const Search = () => { placeholder="Search svgs..." value={search} onChange={handleFilter} + ref={searchRef} /> - {search && !empty && results.length === 0 && ()} - {search && empty && (No results found!)} + {search && !empty && results.length === 0 && ( + + + + )} + {search && empty && No results found!} {results && results.length > 0 && ( <> - + {results.map((item: SVGCardProps) => ( diff --git a/src/interfaces/components.ts b/src/interfaces/components.ts index 31ccdf7..b7c5ea8 100644 --- a/src/interfaces/components.ts +++ b/src/interfaces/components.ts @@ -42,3 +42,7 @@ export interface ErrorProps { title: string; description: string; } + +export interface SearchProps { + availableFocus?: boolean; +} diff --git a/src/layout/header/index.tsx b/src/layout/header/index.tsx index e6eebe4..e8552da 100644 --- a/src/layout/header/index.tsx +++ b/src/layout/header/index.tsx @@ -91,7 +91,7 @@ const Header = () => { - +