import { useState, useEffect, Fragment } from "react"; import { useTranslation } from "next-i18next"; import { FiSearch } from "react-icons/fi"; import { SiDuckduckgo, SiMicrosoftbing, SiGoogle, SiBaidu, SiBrave } from "react-icons/si"; import { Listbox, Transition } from "@headlessui/react"; export const searchProviders = { google: { name: "Google", url: "https://www.google.com/search?q=", icon: SiGoogle, }, duckduckgo: { name: "DuckDuckGo", url: "https://duckduckgo.com/?q=", icon: SiDuckduckgo, }, bing: { name: "Bing", url: "https://www.bing.com/search?q=", icon: SiMicrosoftbing, }, baidu: { name: "Baidu", url: "https://www.baidu.com/s?wd=", icon: SiBaidu, }, brave: { name: "Brave", url: "https://search.brave.com/search?q=", icon: SiBrave, }, custom: { name: "Custom", url: false, icon: FiSearch, }, }; function classNames(...classes) { return classes.filter(Boolean).join(" "); } function useProviderState() { const key = "search-name"; const [value, setValue] = useState(providers.google); useEffect(() => { const storedName = localStorage.getItem(key); let storedProvider = null; if (storedName) { storedProvider = Object.values(providers).find((el) => el.name === storedName); if (storedProvider) { setValue(storedProvider); } } }, []); return [ value, (val) => { setValue(val); localStorage.setItem(key, val.name); }, ]; } function getAvailableProviderIds(options) { if (options.providers && Array.isArray(options.providers)) { return Object.keys(providers).filter((value) => options.providers.includes(value)); } return null; } export default function Search({ options }) { const { t } = useTranslation(); const provider = searchProviders[options.provider]; const [query, setQuery] = useState(""); const [selectedProvider, setSelectedProvider] = useProviderState(); const availableProviderIds = getAvailableProviderIds(options); if (!provider && !availableProviderIds) { return null; } function handleSubmit(event) { const q = encodeURIComponent(query); const url = provider ? provider.url : selectedProvider.url; if (url) { window.open(`${url}${q}`, options.target || "_blank"); } else { window.open(`${options.url}${q}`, options.target || "_blank"); } event.preventDefault(); event.target.reset(); setQuery(""); } const multiProviders = () => (
{t("search.search")}
{availableProviderIds.map((providerId) => { const p = providers[providerId]; return ( {({ active }) => (
  • )}
    ); })}
    ); const singleProvider = () => ( ); return (
    setQuery(s.currentTarget.value)} required autoCapitalize="off" autoCorrect="off" autoComplete="off" // eslint-disable-next-line jsx-a11y/no-autofocus autoFocus={options.focus} /> {provider ? singleProvider() : multiProviders()} ); }