Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add search history menu to site search input #482

Merged
merged 3 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,13 @@
padding: 0.2em 0 0.2em 1em;
text-align: left;

&:focus,
&:active,
&:hover {
background: #dedede;
&[tabindex] {
cursor: pointer;
&:focus,
&:active,
&:hover {
background: #dedede;
}
}

&:first-child {
Expand All @@ -184,7 +187,7 @@
}
}

button {
> button {
border: none;
border-radius: 0;
background: #6c757d;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useStorageBackedState } from '@veupathdb/wdk-client/lib/Hooks/StorageBackedState';
import {
arrayOf,
decodeOrElse,
string,
} from '@veupathdb/wdk-client/lib/Utils/Json';

export function useRecentSearches() {
return useStorageBackedState(
window.localStorage,
[],
'site-search/history',
JSON.stringify,
(value) => decodeOrElse(arrayOf(string), [], value)
);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isEmpty } from 'lodash';
import { isEmpty, uniq } from 'lodash';
import React, { useCallback, useEffect, useRef } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Tooltip } from '@veupathdb/wdk-client/lib/Components';
Expand All @@ -14,9 +14,10 @@ import {
ORGANISM_PARAM,
FILTERS_PARAM,
} from './SiteSearchConstants';
import { TypeAheadInput } from './TypeAheadInput';
import { useRecentSearches } from './SiteSearchHooks';

import './SiteSearch.scss';
import { TypeAheadInput } from './TypeAheadInput';

const cx = makeClassNameHelper('SiteSearch');

Expand Down Expand Up @@ -58,27 +59,51 @@ export const SiteSearchInput = wrappable(function ({
const hasFilters =
!isEmpty(docType) || !isEmpty(organisms) || !isEmpty(fields);

const [recentSearches, setRecentSearches] = useRecentSearches();

const onSearch = useCallback(
(queryString: string) => {
history.push(`${SITE_SEARCH_ROUTE}?${queryString}`);
},
[history]
);

const saveSearchString = useCallback(() => {
if (inputRef.current?.value) {
setRecentSearches(
uniq([inputRef.current.value].concat(recentSearches)).slice(0, 10)
);
}
}, [setRecentSearches, recentSearches]);

const handleSubmitWithFilters = useCallback(() => {
const { current } = formRef;
if (current == null) return;
const formData = new FormData(current);
const queryString = new URLSearchParams(formData as any).toString();
onSearch(queryString);
}, [onSearch]);
saveSearchString();
}, [onSearch, saveSearchString]);

const handleSubmitWithoutFilters = useCallback(() => {
const queryString = `q=${encodeURIComponent(
inputRef.current?.value || ''
)}`;
onSearch(queryString);
}, [onSearch]);
saveSearchString();
}, [onSearch, saveSearchString]);

const handleSubmitWithRecentSearch = useCallback(
(searchString: string) => {
const queryString = `q=${encodeURIComponent(searchString)}`;
onSearch(queryString);
},
[onSearch]
);

const clearRecentSearches = useCallback(() => {
setRecentSearches([]);
}, [setRecentSearches]);

const [lastSearchQueryString, setLastSearchQueryString] =
useSessionBackedState<string>(
Expand Down Expand Up @@ -132,6 +157,9 @@ export const SiteSearchInput = wrappable(function ({
inputReference={inputRef}
searchString={searchString}
placeHolderText={placeholderText}
recentSearches={recentSearches}
onRecentSearchSelect={handleSubmitWithRecentSearch}
onClearRecentSearches={clearRecentSearches}
/>
{location.pathname !== SITE_SEARCH_ROUTE && lastSearchQueryString && (
<Tooltip content="Go back to your last search result">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
FetchClient,
ioTransformer,
} from '@veupathdb/http-utils';
import { useUITheme } from '@veupathdb/coreui/lib/components/theming';

// region Keyboard

Expand Down Expand Up @@ -224,19 +225,25 @@ export interface TypeAheadInputProps {
readonly inputReference: React.RefObject<HTMLInputElement>;
readonly searchString: string;
readonly placeHolderText?: string;
readonly recentSearches: string[];
readonly onRecentSearchSelect: (recentSearch: string) => void;
readonly onClearRecentSearches: () => void;
}

export function TypeAheadInput(props: TypeAheadInputProps): JSX.Element {
const [suggestions, setSuggestions] = useState<Array<string>>([]);
const [hintValue, setHintValue] = useState('');
const [inputValue, setInputValue] = useState(props.searchString);
// "focus" follows mouse clicks, but not tabbing
const [hasFocus, setHasFocus] = useState(false);

const typeAheadAPI = new TypeAheadAPI({
baseUrl: ((ep) => (ep.endsWith('/') ? ep : ep + '/') + TYPEAHEAD_PATH)(
props.siteSearchURL
),
});
const ulReference = useRef<HTMLUListElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const ulClassName =
suggestions.length == 0 ? 'type-ahead-hints hidden' : 'type-ahead-hints';

Expand Down Expand Up @@ -422,6 +429,11 @@ export function TypeAheadInput(props: TypeAheadInputProps): JSX.Element {
else if (kbIsEscape(e)) {
resetInput();
}

// If an item is selected, remove "focus"
else if (kbIsEnter(e)) {
setHasFocus(false);
}
};

const typeAhead = debounce((fn: () => string) => {
Expand All @@ -440,6 +452,16 @@ export function TypeAheadInput(props: TypeAheadInputProps): JSX.Element {
if (lastWordOf(element.value).length >= 3) typeAhead(() => element.value);
};

const selectRecentSearch = (recentSearch: string) => {
props.onRecentSearchSelect(recentSearch);
setInputValue(recentSearch);
setHasFocus(false);
};

// Show history if input is empty, or if input matches the term in the url
const showHistory =
hasFocus && (inputValue === '' || props.searchString === inputValue);

const suggestionItems = suggestions.map((suggestion) => (
<li
className="type-ahead-hint"
Expand All @@ -454,37 +476,76 @@ export function TypeAheadInput(props: TypeAheadInputProps): JSX.Element {
</li>
));

const clickHandler = (e: MouseEvent) => {
if (
e.target instanceof HTMLElement &&
e.target.parentElement !== ulReference.current
)
setSuggestions([]);
};
const historyMenu = props.recentSearches.length
? [
<li className="type-ahead-hint">
<strong>Your recent searches</strong>
</li>,
...props.recentSearches.map((recentSearch) => (
<li
key={recentSearch}
className="type-ahead-hint"
tabIndex={0}
onClick={() => selectRecentSearch(recentSearch)}
onKeyDown={(e) => {
if (kbIsEnter(e)) {
selectRecentSearch(recentSearch);
}
}}
>
{recentSearch}
</li>
)),
<li
className="type-ahead-hint link"
tabIndex={0}
onClick={props.onClearRecentSearches}
onKeyDown={(e) => {
if (kbIsEnter(e)) {
props.onClearRecentSearches();
}
}}
>
Clear search history
</li>,
]
: null;

useEffect(() => {
const clickHandler = (e: MouseEvent) => {
if (!(e.target instanceof HTMLElement)) return;
if (e.target.parentElement !== ulReference.current) {
setSuggestions([]);
}
if (!containerRef.current?.contains(e.target)) {
setHasFocus(false);
}
};

document.addEventListener('click', clickHandler);
return () => removeEventListener('click', clickHandler);
return () => {
removeEventListener('click', clickHandler);
};
}, []);

return (
<div className="type-ahead">
<div ref={containerRef} className="type-ahead">
<div className="type-ahead-input">
<input
name={SEARCH_TERM_PARAM}
type="input"
ref={props.inputReference}
value={inputValue}
defaultValue={props.searchString}
key={props.searchString}
onChange={onInputChange}
onKeyDown={onInputKeyDown}
placeholder={props.placeHolderText}
onClick={() => setHasFocus(true)}
/>
<input type="text" value={hintValue} tabIndex={-1} />
</div>
<ul className={ulClassName} ref={ulReference}>
{suggestionItems}
{showHistory ? historyMenu : suggestionItems}
</ul>
</div>
);
Expand Down
Loading