dashboard/src/components/searchBar.tsx

78 lines
1.7 KiB
TypeScript
Raw Normal View History

import React, { useState } from "react";
2020-07-08 19:36:36 +02:00
import styled from "styled-components";
import selectedTheme from "./themeManager";
const SearchInput = styled.input`
width: 100%;
font-size: 1rem;
border: none;
border-bottom: 1px solid ${selectedTheme.accentColor};
background: none;
border-radius: 0;
color: ${selectedTheme.mainColor};
2021-03-11 13:54:38 +01:00
:focus {
outline: none;
}
2020-07-08 19:36:36 +02:00
`;
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) => {
2020-07-10 00:04:47 +02:00
let [input, setInput] = useState("");
2020-07-08 19:36:36 +02:00
const handleSearchQuery = (e: React.FormEvent) => {
2020-07-10 00:04:47 +02:00
var query = 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 = query.split(" ");
let prefix = queryArray[0];
queryArray.shift();
let searchQuery = queryArray.join(" ");
let providerFound = 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 (
2020-07-10 00:04:47 +02:00
<form onSubmit={(e) => handleSearchQuery(e)}>
2020-07-08 19:36:36 +02:00
<SearchInput
type="text"
2020-07-10 00:04:47 +02:00
onChange={(e) => setInput(e.target.value)}
2020-07-08 19:36:36 +02:00
></SearchInput>
<button type="submit" hidden />
</form>
);
};
export default SearchBar;