2020-11-14 00:44:26 +03:00
|
|
|
import { useState } from 'react';
|
2019-01-06 00:25:54 +03:00
|
|
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
|
|
|
import { faSearch as searchIcon } from '@fortawesome/free-solid-svg-icons';
|
2020-01-14 21:59:25 +03:00
|
|
|
import classNames from 'classnames';
|
2018-08-19 21:29:23 +03:00
|
|
|
import './SearchField.scss';
|
|
|
|
|
2018-08-26 00:39:27 +03:00
|
|
|
const DEFAULT_SEARCH_INTERVAL = 500;
|
2020-08-31 19:38:27 +03:00
|
|
|
let timer: NodeJS.Timeout | null;
|
|
|
|
|
2021-02-28 14:56:56 +03:00
|
|
|
interface SearchFieldProps {
|
2020-08-31 19:38:27 +03:00
|
|
|
onChange: (value: string) => void;
|
|
|
|
className?: string;
|
|
|
|
large?: boolean;
|
|
|
|
noBorder?: boolean;
|
2021-11-07 13:03:31 +03:00
|
|
|
initialValue?: string;
|
2020-08-31 19:38:27 +03:00
|
|
|
}
|
|
|
|
|
2021-11-07 13:03:31 +03:00
|
|
|
const SearchField = ({ onChange, className, large = true, noBorder = false, initialValue = '' }: SearchFieldProps) => {
|
|
|
|
const [ searchTerm, setSearchTerm ] = useState(initialValue);
|
2018-08-19 21:29:23 +03:00
|
|
|
|
2020-04-05 17:16:55 +03:00
|
|
|
const resetTimer = () => {
|
2020-08-31 19:38:27 +03:00
|
|
|
timer && clearTimeout(timer);
|
2020-04-05 17:16:55 +03:00
|
|
|
timer = null;
|
|
|
|
};
|
2020-08-31 19:38:27 +03:00
|
|
|
const searchTermChanged = (newSearchTerm: string, timeout = DEFAULT_SEARCH_INTERVAL) => {
|
2020-04-05 17:16:55 +03:00
|
|
|
setSearchTerm(newSearchTerm);
|
2018-08-26 00:39:27 +03:00
|
|
|
|
2018-08-19 21:29:23 +03:00
|
|
|
resetTimer();
|
|
|
|
|
2020-04-05 17:16:55 +03:00
|
|
|
timer = setTimeout(() => {
|
|
|
|
onChange(newSearchTerm);
|
2018-08-19 21:29:23 +03:00
|
|
|
resetTimer();
|
|
|
|
}, timeout);
|
2020-04-05 17:16:55 +03:00
|
|
|
};
|
2018-08-19 21:52:33 +03:00
|
|
|
|
2020-04-05 17:16:55 +03:00
|
|
|
return (
|
|
|
|
<div className={classNames('search-field', className)}>
|
|
|
|
<input
|
|
|
|
type="text"
|
|
|
|
className={classNames('form-control search-field__input', {
|
|
|
|
'form-control-lg': large,
|
|
|
|
'search-field__input--no-border': noBorder,
|
|
|
|
})}
|
2021-08-21 18:53:06 +03:00
|
|
|
placeholder="Search..."
|
2020-04-05 17:16:55 +03:00
|
|
|
value={searchTerm}
|
|
|
|
onChange={(e) => searchTermChanged(e.target.value)}
|
|
|
|
/>
|
|
|
|
<FontAwesomeIcon icon={searchIcon} className="search-field__icon" />
|
|
|
|
<div
|
|
|
|
className="close search-field__close"
|
|
|
|
hidden={searchTerm === ''}
|
|
|
|
id="search-field__close"
|
|
|
|
onClick={() => searchTermChanged('', 0)}
|
|
|
|
>
|
|
|
|
×
|
2018-08-19 21:29:23 +03:00
|
|
|
</div>
|
2020-04-05 17:16:55 +03:00
|
|
|
</div>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default SearchField;
|