Updates to search component

This commit is contained in:
Sean Edmunds
2025-09-02 17:13:15 -05:00
parent ef630adcbb
commit 93faf9b02a
9 changed files with 530 additions and 247 deletions

View File

@@ -1,5 +1,13 @@
import { Group, type OptionsFilter, Overlay, Select, Stack, Text } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import {
Card,
Group,
type OptionsFilter,
Overlay,
Select,
Stack,
Text,
} from '@mantine/core';
import { useDisclosure, useElementSize } from '@mantine/hooks';
import { HelpModal, WeatherModal } from 'components';
import { useCommonHooks, useMutationAPI, useQueryAPI } from 'hooks';
import { useEffect, useState } from 'react';
@@ -9,6 +17,7 @@ import * as vsc from 'react-icons/vsc';
import { selectClasses } from 'styles';
import type {
Application,
Bookmark,
CurrentWeather,
ExtendedForecast,
Provider,
@@ -29,6 +38,7 @@ export default function Search({
closeWeatherModal: () => void;
openWeatherModal: () => void;
}) {
const { ref, height } = useElementSize();
const allIcons: any = { ...fa6, ...vsc, ...si };
const { data: providerData, isFetched: providerDataIsFetched } = useQueryAPI({
endpoint: 'api/providers',
@@ -37,11 +47,15 @@ export default function Search({
const { data: applicationData, isFetching: isApplicationDataFetching } = useQueryAPI({
endpoint: 'api/enabledApplications',
});
const { data: bookmarkData, isFetched: bookmarksIsFetched } = useQueryAPI({
endpoint: 'api/bookmarks',
});
const { data: defaultProviderData, isFetched: defaultProviderDataIsFetched } =
useQueryAPI({
endpoint: 'api/providers/default',
});
const [applications, setApplications] = useState<Application[]>([]);
const [bookmarks, setBookmarks] = useState<Bookmark[]>([]);
const searchEndpoint = 'api/searchHistory';
const { data: historyData, isFetched: historyDataIsFetched } = useQueryAPI({
endpoint: searchEndpoint,
@@ -52,7 +66,7 @@ export default function Search({
const [providerModalOpened, { open: openProviderModal, close: closeProviderModal }] =
useDisclosure(false);
const [dropdownOpened, { open: openDropdown, close: closeDropdown }] = useDisclosure();
const [listIndex, setListIndex] = useState(0);
const [listIndex, setListIndex] = useState(-1);
const {
isMobile,
urlPattern,
@@ -73,9 +87,12 @@ export default function Search({
} = useCommonHooks();
const [placeholderValue, setPlaceholderValue] = useState<string>('');
const [value, setValue] = useState(0);
const [historyMult, setHistoryMult] = useState(1);
const handleResetSearch = () => {
setSearchValue('');
setListIndex(-1);
setHistoryMult(1);
setProviderLabel(defaultProviderLabel);
setProviderURL(defaultProviderURL);
};
@@ -137,7 +154,7 @@ export default function Search({
if (/^(https?:\/\/).*/i.test(item.target.value))
window.location = item.target.value;
else open(`https://${item.target.value}`, '_self');
} else {
} else if (item.target.value !== '') {
mutateAsync({
method: 'POST',
endpoint: searchEndpoint,
@@ -145,13 +162,15 @@ export default function Search({
}).then(() => {
open(`${providerURL}${subtext}`, '_self');
});
} else {
open(`${providerURL}${subtext}`, '_self');
}
}
};
const handleKeyUp = (item: any) => {
if (item.code === 'Escape') {
setListIndex(0);
setListIndex(-1);
handleResetSearch();
setPlaceholderValue('');
if (dropdownOpened) {
@@ -277,17 +296,28 @@ export default function Search({
};
});
}
return options
.filter((option: any) => {
return splittedSearch.every((searchWord) =>
option.value
.toLowerCase()
.trim()
.split(' ')
.some((word: string) => word.includes(searchWord)),
);
})
.slice(0, 10);
return [
...options
.filter((option: any) => {
return splittedSearch.every((searchWord) =>
option.value
.toLowerCase()
.trim()
.split(' ')
.some((word: string) => word.includes(searchWord)),
);
})
.slice(0, 10 * historyMult),
{
label: 'Load more history...',
value: 'load',
id: 0,
dateTimeStamp: '',
prefix: '',
provider: '',
searchTerm: '',
},
];
};
useEffect(() => {
@@ -302,11 +332,23 @@ export default function Search({
}
}, [applicationData, isApplicationDataFetching]);
useEffect(() => {
if (bookmarkData && bookmarksIsFetched) {
setBookmarks(
bookmarkData.filter(
(bookmark: Bookmark) =>
bookmark.enabled === 1 &&
bookmark.name.toLowerCase().includes(searchValue.toLowerCase()),
),
);
}
}, [bookmarksIsFetched, bookmarkData, searchValue]);
useEffect(() => {
if (historyData && historyDataIsFetched) {
setSearchHistory(historyData);
if (filteredHistory.length === 0) {
setFilteredHistory(historyData.slice(0, 10));
setFilteredHistory(historyData.slice(0, 10 * historyMult));
}
}
}, [historyData, historyDataIsFetched]);
@@ -323,15 +365,13 @@ export default function Search({
useEffect(() => {
const splittedSearch = searchValue.toLowerCase().trim().split(' ');
const filtered = searchHistory
.filter((item: SearchHistoryItem) => {
const option = `${item.prefix} ${item.searchTerm}`;
const words = option.toLowerCase().trim().split(' ');
return splittedSearch.every((searchWord) =>
words.some((word: string) => word.includes(searchWord)),
);
})
.slice(0, 10);
const filtered = searchHistory.filter((item: SearchHistoryItem) => {
const option = `${item.prefix} ${item.searchTerm}`;
const words = option.toLowerCase().trim().split(' ');
return splittedSearch.every((searchWord) =>
words.some((word: string) => word.includes(searchWord)),
);
});
setFilteredHistory(filtered);
}, [searchValue]);
@@ -344,7 +384,6 @@ export default function Search({
setDefaultProviderLabel(defaultProviderData[0]?.name ?? 'Google Search');
}
}, [defaultProviderData, defaultProviderDataIsFetched]);
return (
<>
{dropdownOpened && <Overlay blur={5} />}
@@ -358,8 +397,12 @@ export default function Search({
display: 'inline-block',
gap: 0,
}}
align='center'
justify='center'
w={'100%'}
>
<Select
ref={ref}
classNames={selectClasses}
data={searchHistory.map((item: SearchHistoryItem) => ({
label: `${item.provider}`,
@@ -387,15 +430,47 @@ export default function Search({
searchable
autoFocus={!isMobile}
leftSection={providerLabel}
rightSection={<div />}
rightSection={searchValue === '' ? <div /> : undefined}
clearable
onClear={handleResetSearch}
clearButtonProps={{
'aria-label': 'Clear search',
style: { color: 'var(--mantine-color-accent-0)', marginRight: '.5rem' },
}}
scrollAreaProps={{ viewportRef: ref }}
renderOption={(item: any) => {
const Icon = allIcons[item.option.icon];
return !searchValue.startsWith('!') ? (
<SearchSelectItem
item={item}
handleSearchHistoryItem={handleSearchHistoryItem}
searchEndpoint={searchEndpoint}
/>
item.option.value === 'load' ? (
<Group
pos={'relative'}
m={0}
p={0}
gap={0}
w={'100%'}
h={'2rem'}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setHistoryMult((prev: number) => prev + 1);
}}
>
<Text
w={'100%'}
c={'var(--mantine-color-accent-0)'}
style={{ textAlign: 'center' }}
>
{item.option.label}
</Text>
</Group>
) : (
<SearchSelectItem
item={item}
handleSearchHistoryItem={handleSearchHistoryItem}
searchEndpoint={searchEndpoint}
setSearchValue={setSearchValue}
/>
)
) : (
<Group
pos={'relative'}
@@ -430,7 +505,7 @@ export default function Search({
}}
onBlur={() => {
setPlaceholderValue('');
setListIndex(0);
setListIndex(-1);
closeDropdown();
}}
onFocus={() => {
@@ -443,9 +518,80 @@ export default function Search({
e.preventDefault();
}
}}
onDoubleClick={() => {
dropdownOpened ? closeDropdown() : openDropdown();
}}
onInput={onInput}
onKeyUp={handleKeyUp}
/>
{dropdownOpened && (
<Group w={'100%'} justify='center'>
<Card
w={'100%'}
mt={`calc(${height}px + 1.5rem)`}
pos={'relative'}
style={{
zIndex: 1000,
opacity: searchValue && dropdownOpened && bookmarks.length > 0 ? 1 : 0,
background: 'transparent',
}}
>
<Stack gap={8}>
<Group
w={'100%'}
p={'1rem'}
style={{
backgroundColor: 'var(--mantine-color-search-0)',
backdropFilter: 'blur(15px) brightness(1.75)',
borderRadius: '10px',
}}
>
<Text c={'var(--mantine-color-primary-0)'} fz={'1.5rem'}>
Recommended items:
</Text>
</Group>
<Group
w={'50%'}
p={'1rem'}
justify='center'
style={{
backgroundColor: 'var(--mantine-color-search-0)',
backdropFilter: 'blur(15px) brightness(1.75)',
borderRadius: '10px',
}}
>
<Stack>
<Text
c={'var(--mantine-color-primary-0)'}
fz={'1.25rem'}
style={{ fontWeight: 'bold', textDecoration: 'underline' }}
>
Bookmarks
</Text>
{bookmarks
.map((bookmark: Bookmark) => (
<Text
key={bookmark.name}
component='a'
href={bookmark.url}
c={'var(--mantine-color-primary-0)'}
style={{
backgroundColor: 'var(--mantine-color-search-0)',
padding: '.5rem',
borderRadius: '10px',
}}
>
{bookmark.name}
</Text>
))
.toSorted((a: any, b: any) => (a.key > b.key ? 1 : -1))
.slice(0, 5)}
</Stack>
</Group>
</Stack>
</Card>
</Group>
)}
<HelpModal
handleResetSearch={handleResetSearch}
applicationData={applications}

View File

@@ -1,11 +1,16 @@
import { ActionIcon, Group, Text } from '@mantine/core';
import { useCommonHooks, useMutationAPI } from 'hooks';
import { useState } from 'react';
import { FiEdit, FiTrash } from 'react-icons/fi';
import { FiArrowUpRight, FiTrash } from 'react-icons/fi';
import { actionIconClasses } from 'styles';
function SearchSelectItem({ item, handleSearchHistoryItem, searchEndpoint }: any) {
const { isMobile, theme, setSearchValue } = useCommonHooks();
function SearchSelectItem({
item,
handleSearchHistoryItem,
searchEndpoint,
setSearchValue,
}: any) {
const { isMobile, theme } = useCommonHooks();
const { mutateAsync } = useMutationAPI();
const [showFillButton, setShowFillButton] = useState(false);
const m = new Date(item.option.dateTimeStamp);
@@ -17,11 +22,11 @@ function SearchSelectItem({ item, handleSearchHistoryItem, searchEndpoint }: any
const dateString = isMobile
? `${month}/${day}/${year}`
: `${month}/${day}/${year} ${hours}:${minutes}`;
return (
<Group
w={'100%'}
display={'flex'}
justify={'space-between'}
gap={0}
onClick={() => {
handleSearchHistoryItem(item);
@@ -33,7 +38,7 @@ function SearchSelectItem({ item, handleSearchHistoryItem, searchEndpoint }: any
setShowFillButton(false);
}}
>
<Group m={0} p={0} miw={'160px'}>
<Group m={0} p={0} w={'160px'}>
<Text
style={{
backgroundColor: `${theme.primaryColor}33`,
@@ -44,25 +49,13 @@ function SearchSelectItem({ item, handleSearchHistoryItem, searchEndpoint }: any
>
{item.option.provider}
</Text>
{showFillButton && (
<ActionIcon
className={actionIconClasses.selectOptionActions}
classNames={actionIconClasses}
onClick={(e) => {
e.stopPropagation();
setSearchValue(`${item.option.prefix} ${item.option.searchTerm}`);
}}
>
<FiEdit />
</ActionIcon>
)}
</Group>
<Group
m={0}
p={0}
gap={0}
justify='space-between'
w={'65%'}
w={'calc(100% - 160px)'}
style={{
whiteSpace: 'nowrap',
overflow: 'hidden',
@@ -90,8 +83,19 @@ function SearchSelectItem({ item, handleSearchHistoryItem, searchEndpoint }: any
{dateString}
</Text>
</Group>
<Group m={0} p={0} right={'1rem'} w={'24px'}>
{showFillButton && (
{showFillButton && (
<Group m={0} p={0} gap={0} right={'8rem'} w={'fit-content'} pos={'absolute'}>
<ActionIcon
className={actionIconClasses.selectOptionActions}
classNames={actionIconClasses}
onClick={(e) => {
e.stopPropagation();
setSearchValue(`${item.option.prefix} ${item.option.searchTerm}`);
}}
>
<FiArrowUpRight />
</ActionIcon>
<ActionIcon
className={actionIconClasses.selectOptionActions}
classNames={actionIconClasses}
@@ -106,8 +110,8 @@ function SearchSelectItem({ item, handleSearchHistoryItem, searchEndpoint }: any
>
<FiTrash />
</ActionIcon>
)}
</Group>
</Group>
)}
</Group>
);
}