2023-06-02 09:41:34 +05:30
|
|
|
import { forwardRef, useState, useEffect } from 'react';
|
|
|
|
|
import { Search, X } from 'lucide-react';
|
2023-03-29 00:08:02 +08:00
|
|
|
import { useRecoilState } from 'recoil';
|
2023-03-28 20:36:21 +08:00
|
|
|
import store from '~/store';
|
2023-03-18 01:40:49 -04:00
|
|
|
|
2023-05-19 16:02:41 -04:00
|
|
|
const SearchBar = forwardRef((props, ref) => {
|
|
|
|
|
const { clearSearch } = props;
|
2023-04-06 05:47:37 -07:00
|
|
|
const [searchQuery, setSearchQuery] = useRecoilState(store.searchQuery);
|
2023-06-02 09:41:34 +05:30
|
|
|
const [showClearIcon, setShowClearIcon] = useState(false);
|
2023-03-29 00:08:02 +08:00
|
|
|
|
2023-05-18 11:09:31 -07:00
|
|
|
const handleKeyUp = (e) => {
|
2023-03-18 01:40:49 -04:00
|
|
|
const { value } = e.target;
|
2023-03-28 20:36:21 +08:00
|
|
|
if (e.keyCode === 8 && value === '') {
|
|
|
|
|
setSearchQuery('');
|
2023-03-18 14:28:10 -04:00
|
|
|
clearSearch();
|
2023-03-18 01:40:49 -04:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2023-05-18 15:22:48 -04:00
|
|
|
const onChange = (e) => {
|
|
|
|
|
const { value } = e.target;
|
|
|
|
|
setSearchQuery(value);
|
2023-06-02 09:41:34 +05:30
|
|
|
setShowClearIcon(value.length > 0);
|
2023-05-18 15:22:48 -04:00
|
|
|
};
|
|
|
|
|
|
2023-06-02 09:41:34 +05:30
|
|
|
useEffect(() => {
|
|
|
|
|
if (searchQuery.length === 0) {
|
|
|
|
|
setShowClearIcon(false);
|
|
|
|
|
} else {
|
|
|
|
|
setShowClearIcon(true);
|
|
|
|
|
}
|
|
|
|
|
}, [searchQuery])
|
|
|
|
|
|
2023-03-18 01:40:49 -04:00
|
|
|
return (
|
2023-05-19 16:02:41 -04:00
|
|
|
<div
|
|
|
|
|
ref={ref}
|
2023-06-02 09:41:34 +05:30
|
|
|
className="flex w-full cursor-pointer items-center gap-3 px-3 py-3 text-sm text-white transition-colors duration-200 hover:bg-gray-700 relative"
|
2023-05-19 16:02:41 -04:00
|
|
|
>
|
2023-06-02 09:41:34 +05:30
|
|
|
{<Search className="h-4 w-4 absolute left-3" />}
|
2023-03-18 01:40:49 -04:00
|
|
|
<input
|
|
|
|
|
type="text"
|
2023-06-02 09:41:34 +05:30
|
|
|
className="m-0 mr-0 w-full border-none bg-transparent p-0 text-sm leading-tight outline-none pl-7"
|
2023-04-06 05:47:37 -07:00
|
|
|
value={searchQuery}
|
2023-05-18 15:22:48 -04:00
|
|
|
onChange={onChange}
|
|
|
|
|
onKeyDown={(e) => {
|
|
|
|
|
e.code === 'Space' ? e.stopPropagation() : null;
|
|
|
|
|
}}
|
2023-03-18 01:40:49 -04:00
|
|
|
placeholder="Search messages"
|
|
|
|
|
onKeyUp={handleKeyUp}
|
|
|
|
|
/>
|
2023-06-02 09:41:34 +05:30
|
|
|
<X
|
|
|
|
|
className={`h-5 w-5 absolute right-3 cursor-pointer ${showClearIcon ? 'opacity-100' : 'opacity-0'} transition-opacity duration-1000`}
|
|
|
|
|
onClick={() => {
|
|
|
|
|
setSearchQuery('');
|
|
|
|
|
clearSearch();
|
|
|
|
|
}}
|
|
|
|
|
/>
|
2023-03-18 01:40:49 -04:00
|
|
|
</div>
|
|
|
|
|
);
|
2023-05-19 16:02:41 -04:00
|
|
|
});
|
|
|
|
|
|
2023-06-02 09:41:34 +05:30
|
|
|
export default SearchBar;
|