Added production support for search

This commit is contained in:
Bastian Meissner 2020-05-22 00:34:52 +02:00
parent c2d5a90df5
commit 19bbc337bf
2 changed files with 56 additions and 22 deletions

View file

@ -1,7 +1,7 @@
{
"apps": [
{
"name": "my pi hole",
"name": "Pihole",
"displayURL": "example.com",
"URL": "https://example.com",
"icon": "vpn_lock"

View file

@ -1,7 +1,7 @@
import React, { useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import searchData from './data/search.json';
import { ErrorMessage } from './elements';
import selectedTheme from './themeManager';
@ -15,29 +15,40 @@ const SearchInput = styled.input`
color: ${selectedTheme.mainColor};
`;
const handleQueryWithProvider = query => {
let queryArray = query.split(' ');
let prefix = queryArray[0];
queryArray.shift();
let searchQuery = queryArray.join(' ');
var foundProvider = false;
searchData.providers.forEach(provider => {
if (provider.prefix === prefix) {
foundProvider = true;
window.location = provider.url + searchQuery;
}
});
if (!foundProvider) {
window.location = 'https://google.com/search?q=' + query;
const handleResponse = response => {
if (response.ok) {
return response.json();
}
throw new Error('Failed to load app data.');
};
const useSearchProviders = () => {
const [searchProviders, setSearchProviders] = useState({
providers: [],
error: false
});
const fetchSearchProviders = useCallback(() => {
(process.env.NODE_ENV === 'production'
? fetch('/search.json').then(handleResponse)
: import('./data/search.json')
)
.then(jsonResponse => {
setSearchProviders({ ...jsonResponse, error: false });
})
.catch(error => {
setSearchProviders({ providers: [], error: error.message });
});
}, []);
useEffect(() => {
fetchSearchProviders();
}, [fetchSearchProviders]);
return searchProviders;
};
const SearchBar = () => {
const searchProviders = useSearchProviders();
let [input, setInput] = useState();
const handleSearchQuery = e => {
@ -52,8 +63,31 @@ const SearchBar = () => {
e.preventDefault();
};
const handleQueryWithProvider = query => {
let queryArray = query.split(' ');
let prefix = queryArray[0];
queryArray.shift();
let searchQuery = queryArray.join(' ');
var foundProvider = false;
searchProviders.providers.forEach(provider => {
if (provider.prefix === prefix) {
foundProvider = true;
window.location = provider.url + searchQuery;
}
});
if (!foundProvider) {
window.location = 'https://google.com/search?q=' + query;
}
};
return (
<form onSubmit={e => handleSearchQuery(e)}>
{searchProviders.error && (
<ErrorMessage>{searchProviders.error}</ErrorMessage>
)}
<SearchInput
type="text"
onChange={e => setInput(e.target.value)}