dashboard/src/components/searchBar.tsx

117 lines
2.5 KiB
TypeScript
Raw Normal View History

import React, { useEffect, useState } from "react";
2020-07-08 19:36:36 +02:00
import styled from "styled-components";
import selectedTheme from "./themeManager";
import { Button } from "./elements";
const Search = styled.form`
width: 100%;
height: 2rem;
display: flex;
padding-top: 0.25rem;
`;
2020-07-08 19:36:36 +02:00
const SearchInput = styled.input`
width: 100%;
2020-07-08 19:36:36 +02:00
font-size: 1rem;
2020-07-08 19:36:36 +02:00
border: none;
border-bottom: 1px solid ${selectedTheme.accentColor};
2020-07-08 19:36:36 +02:00
background: none;
border-radius: 0;
color: ${selectedTheme.mainColor};
2021-03-11 13:54:38 +01:00
margin: 0px;
2021-03-11 13:54:38 +01:00
:focus {
outline: none;
}
2020-07-08 19:36:36 +02:00
`;
const SearchButton = styled(Button)`
margin: 0px 2px;
min-height: 0;
`;
export interface ISearchProviderProps {
name: string;
url: string;
prefix: string;
}
2020-07-08 19:36:36 +02:00
interface ISearchBarProps {
providers: Array<ISearchProviderProps> | undefined;
}
2020-07-08 19:36:36 +02:00
const SearchBar = ({ providers }: ISearchBarProps) => {
let [input, setInput] = useState<string>("");
let [buttonsHidden, setButtonsHidden] = useState<boolean>(true);
useEffect(() => {
setButtonsHidden(input === "");
}, [input]);
2020-07-08 19:36:36 +02:00
const handleSearchQuery = (e: React.FormEvent) => {
var query: string = input || "";
2020-07-08 19:36:36 +02:00
if (query.split(" ")[0].includes("/")) {
handleQueryWithProvider(query);
} else {
window.location.href = "https://google.com/search?q=" + query;
}
e.preventDefault();
};
const handleQueryWithProvider = (query: string) => {
let queryArray: Array<string> = query.split(" ");
let prefix: string = queryArray[0];
2020-07-08 19:36:36 +02:00
queryArray.shift();
let searchQuery: string = queryArray.join(" ");
2020-07-08 19:36:36 +02:00
let providerFound: boolean = false;
if (providers) {
providers.forEach((provider: ISearchProviderProps) => {
if (provider.prefix === prefix) {
providerFound = true;
window.location.href = provider.url + searchQuery;
}
});
}
2020-07-08 19:36:36 +02:00
if (!providerFound)
window.location.href = "https://google.com/search?q=" + query;
};
return (
<Search onSubmit={(e) => handleSearchQuery(e)}>
2020-07-08 19:36:36 +02:00
<SearchInput
type="text"
value={input}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setInput(e.target.value)
}
2020-07-08 19:36:36 +02:00
></SearchInput>
<SearchButton
type="button"
onClick={() => setInput("")}
hidden={buttonsHidden}
>
Clear
</SearchButton>
<SearchButton type="submit" hidden={buttonsHidden}>
Search
</SearchButton>
</Search>
2020-07-08 19:36:36 +02:00
);
};
export default SearchBar;