284 lines
8.4 KiB
TypeScript
284 lines
8.4 KiB
TypeScript
import { Group, type OptionsFilter, Select, Stack, Text } from '@mantine/core';
|
|
import { useDisclosure } from '@mantine/hooks';
|
|
import { HelpModal, WeatherModal } from 'components';
|
|
import { useCommonHooks, useMutationAPI, useQueryAPI } from 'hooks';
|
|
import { useEffect, useState } from 'react';
|
|
import { selectClasses } from 'styles';
|
|
|
|
export default function Search({
|
|
current,
|
|
outlook,
|
|
extendedForecast,
|
|
weatherModalOpened,
|
|
closeWeatherModal,
|
|
openWeatherModal,
|
|
}: any) {
|
|
const { data: providers, isFetched: providersIsFetched } = useQueryAPI({
|
|
endpoint: 'api/providers',
|
|
});
|
|
const [providerData, setProviderData] = useState<any>([]);
|
|
const { data: apps, isFetching: isAppsFetching } = useQueryAPI({
|
|
endpoint: 'api/apps',
|
|
});
|
|
const [applicationData, setApplicationData] = useState<any>([]);
|
|
const { data: history, isFetched: historyIsFetched } = useQueryAPI({
|
|
endpoint: 'api/searchHistory',
|
|
});
|
|
const [searchHistory, setSearchHistory] = useState<any>([]);
|
|
const { mutateAsync: createHistoryItem } = useMutationAPI();
|
|
const [providerModalOpened, { open: openProviderModal, close: closeProviderModal }] =
|
|
useDisclosure(false);
|
|
const [dropdownOpened, { open: openDropdown, close: closeDropdown }] = useDisclosure();
|
|
const {
|
|
theme,
|
|
providerLabel,
|
|
setProviderLabel,
|
|
providerURL,
|
|
setProviderURL,
|
|
providerPrefix,
|
|
setProviderPrefix,
|
|
searchValue,
|
|
setSearchValue,
|
|
} = useCommonHooks();
|
|
|
|
const urlPattern = new RegExp(
|
|
'^(https?:\\/\\/)?' + // protocol
|
|
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
|
|
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
|
|
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
|
|
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
|
|
'(\\#[-a-z\\d_]*)?$',
|
|
'i',
|
|
); // fragment locator
|
|
|
|
const handleSearchHistoryItem = (item: any) => {
|
|
const url =
|
|
providers.find((provider: any) => provider.prefix === item.option.prefix)?.url ||
|
|
'https://www.google.com/search?q=';
|
|
open(`${url}${item.option.searchTerm}`, '_self');
|
|
};
|
|
|
|
const handleKeyPress = (item: any) => {
|
|
let option = '';
|
|
let subtext = '';
|
|
if (item.target.value.startsWith('/')) {
|
|
option =
|
|
item.target.value.substr(1, item.target.value.indexOf(' ') - 1) ||
|
|
item.target.value.substr(1);
|
|
subtext = item.target.value.substr(2 + option.length);
|
|
} else if (item.target.value.startsWith('!')) {
|
|
if (item.target.value.startsWith('!w')) {
|
|
subtext = item.target.value.substr(2);
|
|
}
|
|
} else {
|
|
subtext = item.target.value;
|
|
}
|
|
if (item.key === 'Enter') {
|
|
if (providerLabel === 'Show help') {
|
|
openProviderModal();
|
|
} else if (item.target.value.startsWith('/')) {
|
|
createHistoryItem({
|
|
method: 'POST',
|
|
endpoint: 'api/searchHistory',
|
|
body: { prefix: providerPrefix, provider: providerLabel, searchTerm: subtext },
|
|
}).then(() => {
|
|
open(`${providerURL}${subtext}`, '_self');
|
|
});
|
|
} else if (providerLabel === 'Show weather') {
|
|
openWeatherModal();
|
|
} else if (providerLabel.startsWith('Launch')) {
|
|
open(
|
|
`https://${applicationData?.find((app: any) => app.baseUrl.substr(1).toLowerCase() === item.target.value.substr(1)).url}`,
|
|
'_self',
|
|
);
|
|
} else if (urlPattern.test(item.target.value)) {
|
|
if (/^(https?:\/\/).*/i.test(item.target.value))
|
|
window.location = item.target.value;
|
|
else open(`https://${item.target.value}`, '_self');
|
|
} else {
|
|
createHistoryItem({
|
|
method: 'POST',
|
|
endpoint: 'api/searchHistory',
|
|
body: { prefix: providerPrefix, provider: providerLabel, searchTerm: subtext },
|
|
}).then(() => {
|
|
open(`${providerURL}${subtext}`, '_self');
|
|
});
|
|
}
|
|
}
|
|
};
|
|
|
|
const optionsFilter: OptionsFilter = ({ options, search }) => {
|
|
const splittedSearch = search.toLowerCase().trim().split(' ');
|
|
return options
|
|
.filter((option: any) => {
|
|
const words = option.value.toLowerCase().trim().split(' ');
|
|
return splittedSearch.every((searchWord) =>
|
|
words.some((word: any) => word.includes(searchWord)),
|
|
);
|
|
})
|
|
.slice(0, 10);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (providers && providersIsFetched) {
|
|
setProviderData(providers);
|
|
}
|
|
}, [providers, providersIsFetched]);
|
|
|
|
useEffect(() => {
|
|
if (apps && !isAppsFetching) {
|
|
setApplicationData(apps);
|
|
}
|
|
}, [apps, isAppsFetching]);
|
|
|
|
useEffect(() => {
|
|
if (history && historyIsFetched) {
|
|
setSearchHistory(history);
|
|
}
|
|
}, [history, historyIsFetched]);
|
|
return (
|
|
<Stack
|
|
style={{
|
|
height: '100px',
|
|
backgroundColor: 'transparent',
|
|
textAlign: 'center',
|
|
position: 'relative',
|
|
padding: '.3em',
|
|
display: 'inline-block',
|
|
gap: 0,
|
|
}}
|
|
>
|
|
<Select
|
|
classNames={selectClasses}
|
|
className={selectClasses.search}
|
|
filter={optionsFilter}
|
|
searchable
|
|
data={searchHistory.map((item: any) => ({
|
|
label: `${item.provider}`,
|
|
value: `${item.prefix} ${item.searchTerm} ${item.dateTimeStamp}`,
|
|
...item,
|
|
}))}
|
|
renderOption={(item: any) => {
|
|
const m = new Date(item.option.dateTimeStamp);
|
|
const dateString = `${m.getUTCFullYear()}/${`0${m.getUTCMonth() + 1}`.slice(-2)}/${`0${m.getUTCDate()}`.slice(-2)} ${`0${m.getUTCHours()}`.slice(-2)}:${`0${m.getUTCMinutes()}`.slice(-2)}:${`0${m.getUTCSeconds()}`.slice(-2)}`;
|
|
return (
|
|
<Group
|
|
w={'100%'}
|
|
onClick={() => {
|
|
handleSearchHistoryItem(item);
|
|
}}
|
|
>
|
|
<Group w={'15%'}>
|
|
<Text
|
|
style={{
|
|
backgroundColor: `${theme.primaryColor}33`,
|
|
fontWeight: 600,
|
|
borderRadius: '15px',
|
|
padding: '5px',
|
|
}}
|
|
>
|
|
{item.option.label}
|
|
</Text>
|
|
</Group>
|
|
<Group justify='space-between' w={'80%'}>
|
|
<Text>{item.option.searchTerm}</Text>
|
|
<Text
|
|
style={{
|
|
color: `${theme.primaryColor}33`,
|
|
}}
|
|
>
|
|
{dateString}
|
|
</Text>
|
|
</Group>
|
|
</Group>
|
|
);
|
|
}}
|
|
spellCheck='true'
|
|
leftSection={providerLabel}
|
|
rightSection={<Stack />}
|
|
value={searchValue}
|
|
searchValue={searchValue}
|
|
placeholder={searchValue === '' ? undefined : searchValue}
|
|
nothingFoundMessage='Nothing found...'
|
|
data-active={searchValue !== ''}
|
|
dropdownOpened={dropdownOpened}
|
|
onBlur={() => closeDropdown()}
|
|
onFocus={() => {
|
|
if (searchValue !== '') {
|
|
openDropdown();
|
|
}
|
|
}}
|
|
comboboxProps={{
|
|
withinPortal: false,
|
|
transitionProps: { transition: 'fade', duration: 200 },
|
|
}}
|
|
onInput={(item: any) => {
|
|
openDropdown();
|
|
setSearchValue(item.currentTarget.value);
|
|
if (
|
|
item.target.value === '/?' ||
|
|
item.target.value === '!help' ||
|
|
item.target.value === '/help' ||
|
|
item.target.value === '!h' ||
|
|
item.target.value === '/h'
|
|
) {
|
|
setProviderLabel('Show help');
|
|
} else if (item.target.value.startsWith('/g')) {
|
|
setProviderLabel('Google Search');
|
|
setProviderURL('https://www.google.com/search?q=');
|
|
setProviderPrefix('/g');
|
|
} else if (item.target.value.startsWith('/')) {
|
|
const provider = providerData?.find(
|
|
(p: any) => p.prefix === item.target.value.split(' ')[0],
|
|
);
|
|
setProviderLabel(provider?.name || 'Invalid Search');
|
|
setProviderURL(provider?.url);
|
|
setProviderPrefix(provider?.prefix);
|
|
} else if (item.target.value.startsWith('!')) {
|
|
if (item.target.value === '!w' || item.target.value === '!weather') {
|
|
setProviderLabel('Show weather');
|
|
} else if (
|
|
applicationData?.find(
|
|
(app: any) =>
|
|
app.baseUrl.substr(1).toLowerCase() === item.target.value.substr(1),
|
|
)
|
|
) {
|
|
setProviderLabel(`Launch ${item.target.value.substr(1)}`);
|
|
} else {
|
|
setProviderLabel('Invalid function');
|
|
}
|
|
}
|
|
}}
|
|
onKeyUp={(item: any) => {
|
|
if (item.code === 'Escape') {
|
|
if (dropdownOpened) {
|
|
closeDropdown();
|
|
}
|
|
setSearchValue('');
|
|
setProviderLabel('Google Search');
|
|
setProviderPrefix('/g');
|
|
}
|
|
if (item.code === 'ArrowDown' && !dropdownOpened) {
|
|
openDropdown();
|
|
}
|
|
if (!providerLabel.startsWith('Invalid')) {
|
|
handleKeyPress(item);
|
|
}
|
|
}}
|
|
/>
|
|
<HelpModal
|
|
providerModalOpened={providerModalOpened}
|
|
providerData={providerData}
|
|
closeProviderModal={closeProviderModal}
|
|
/>
|
|
<WeatherModal
|
|
current={current}
|
|
outlook={outlook}
|
|
extendedForecast={extendedForecast}
|
|
closeWeatherModal={closeWeatherModal}
|
|
weatherModalOpened={weatherModalOpened}
|
|
/>
|
|
</Stack>
|
|
);
|
|
}
|