import React, { useEffect, useState } from "react"; import styled from "styled-components"; import selectedTheme from "../lib/theme"; import { Button } from "./elements"; const Search = styled.form` width: 100%; height: 2rem; display: flex; padding-top: 0.25rem; `; const SearchInput = styled.input` width: 100%; margin: 0px; font-size: 1rem; border: none; border-bottom: 1px solid ${selectedTheme.accentColor}; border-radius: 0; background: none; color: ${selectedTheme.mainColor}; :focus { outline: none; } `; const SearchButton = styled(Button)` margin: 0px 2px; min-height: 0; `; export interface ISearchProviderProps { name: string; url: string; prefix: string; } export interface ISearchProps { defaultProvider: string; providers: Array | undefined; } interface ISearchBarProps { search: ISearchProps; } export const handleQueryWithProvider = ( search: ISearchProps, query: string, ) => { let queryArray: Array = query.split(" "); let prefix: string = queryArray[0]; queryArray.shift(); let searchQuery: string = queryArray.join(" "); let providerFound: boolean = false; if (search.providers) { search.providers.forEach((provider: ISearchProviderProps) => { if (provider.prefix === prefix) { providerFound = true; window.location.href = provider.url + searchQuery; } }); } if (!providerFound) window.location.href = search.defaultProvider + query; }; /** * Renders a search bar * @param {ISearchBarProps} search - The search providers for the search bar to use */ const SearchBar = ({ search }: ISearchBarProps) => { let [input, setInput] = useState(""); let [buttonsHidden, setButtonsHidden] = useState(true); useEffect(() => setButtonsHidden(input === ""), [input]); const handleSearchQuery = (e: React.FormEvent) => { var query: string = input || ""; if (query.split(" ")[0].includes("/")) { handleQueryWithProvider(search, query); } else { window.location.href = search.defaultProvider + query; } e.preventDefault(); }; return ( handleSearchQuery(e)}> ) => setInput(e.target.value) } > setInput("")} hidden={buttonsHidden} > Clear ); }; export default SearchBar;