2021-06-25 10:42:44 +02:00
|
|
|
import { useRef, useEffect, KeyboardEvent } from 'react';
|
|
|
|
|
|
|
|
// Redux
|
|
|
|
import { connect } from 'react-redux';
|
|
|
|
import { createNotification } from '../../store/actions';
|
|
|
|
|
|
|
|
// Typescript
|
|
|
|
import { NewNotification } from '../../interfaces';
|
|
|
|
|
|
|
|
// CSS
|
|
|
|
import classes from './SearchBar.module.css';
|
|
|
|
|
|
|
|
// Utils
|
|
|
|
import { searchParser } from '../../utility';
|
|
|
|
|
|
|
|
interface ComponentProps {
|
|
|
|
createNotification: (notification: NewNotification) => void;
|
2021-09-06 12:24:01 +02:00
|
|
|
setLocalSearch: (query: string) => void;
|
2021-06-25 10:42:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const SearchBar = (props: ComponentProps): JSX.Element => {
|
2021-09-06 12:24:01 +02:00
|
|
|
const { setLocalSearch, createNotification } = props;
|
|
|
|
|
2021-06-25 10:42:44 +02:00
|
|
|
const inputRef = useRef<HTMLInputElement>(document.createElement('input'));
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
inputRef.current.focus();
|
2021-09-06 12:24:01 +02:00
|
|
|
}, []);
|
2021-06-25 10:42:44 +02:00
|
|
|
|
|
|
|
const searchHandler = (e: KeyboardEvent<HTMLInputElement>) => {
|
|
|
|
if (e.code === 'Enter') {
|
2021-09-06 12:24:01 +02:00
|
|
|
const searchResult = searchParser(inputRef.current.value);
|
2021-06-25 10:42:44 +02:00
|
|
|
|
2021-09-06 12:24:01 +02:00
|
|
|
if (!searchResult.prefix) {
|
|
|
|
createNotification({
|
2021-06-25 10:42:44 +02:00
|
|
|
title: 'Error',
|
2021-09-06 12:24:01 +02:00
|
|
|
message: 'Prefix not found',
|
|
|
|
});
|
|
|
|
} else if (searchResult.isLocal) {
|
|
|
|
setLocalSearch(searchResult.query);
|
2021-06-25 10:42:44 +02:00
|
|
|
}
|
|
|
|
}
|
2021-09-06 12:24:01 +02:00
|
|
|
};
|
2021-06-25 10:42:44 +02:00
|
|
|
|
|
|
|
return (
|
|
|
|
<input
|
|
|
|
ref={inputRef}
|
2021-09-06 12:24:01 +02:00
|
|
|
type="text"
|
2021-06-25 10:42:44 +02:00
|
|
|
className={classes.SearchBar}
|
|
|
|
onKeyDown={(e) => searchHandler(e)}
|
|
|
|
/>
|
2021-09-06 12:24:01 +02:00
|
|
|
);
|
|
|
|
};
|
2021-06-25 10:42:44 +02:00
|
|
|
|
2021-09-06 12:24:01 +02:00
|
|
|
export default connect(null, { createNotification })(SearchBar);
|