1
0
Fork 0
mirror of https://github.com/pawelmalak/flame.git synced 2025-08-03 18:05:18 +02:00
flame/client/src/components/SearchBar/SearchBar.tsx

82 lines
2.1 KiB
TypeScript
Raw Normal View History

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
2021-10-06 12:01:07 +02:00
import { searchParser, urlParser, redirectUrl } from '../../utility';
interface ComponentProps {
createNotification: (notification: NewNotification) => void;
2021-09-06 12:24:01 +02:00
setLocalSearch: (query: string) => void;
}
const SearchBar = (props: ComponentProps): JSX.Element => {
2021-09-06 12:24:01 +02:00
const { setLocalSearch, createNotification } = props;
const inputRef = useRef<HTMLInputElement>(document.createElement('input'));
useEffect(() => {
inputRef.current.focus();
2021-09-06 12:24:01 +02:00
}, []);
2021-10-13 13:31:01 +02:00
const clearSearch = () => {
inputRef.current.value = '';
setLocalSearch('');
};
const searchHandler = (e: KeyboardEvent<HTMLInputElement>) => {
2021-10-06 12:01:07 +02:00
const { isLocal, search, query, isURL, sameTab } = searchParser(
inputRef.current.value
);
2021-09-06 12:47:17 +02:00
2021-10-06 12:01:07 +02:00
if (isLocal) {
setLocalSearch(search);
2021-09-06 12:47:17 +02:00
}
2021-10-13 13:31:01 +02:00
if (e.code === 'Enter' || e.code === 'NumpadEnter') {
2021-10-06 12:01:07 +02:00
if (!query.prefix) {
2021-10-13 13:31:01 +02:00
// Prefix not found -> emit notification
2021-09-06 12:24:01 +02:00
createNotification({
title: 'Error',
2021-09-06 12:24:01 +02:00
message: 'Prefix not found',
});
2021-10-06 12:01:07 +02:00
} else if (isURL) {
2021-10-13 13:31:01 +02:00
// URL or IP passed -> redirect
2021-10-06 12:01:07 +02:00
const url = urlParser(inputRef.current.value)[1];
redirectUrl(url, sameTab);
} else if (isLocal) {
2021-10-13 13:31:01 +02:00
// Local query -> filter apps and bookmarks
2021-10-06 12:01:07 +02:00
setLocalSearch(search);
2021-09-06 12:47:17 +02:00
} else {
2021-10-13 13:31:01 +02:00
// Valid query -> redirect to search results
2021-10-06 12:01:07 +02:00
const url = `${query.template}${search}`;
redirectUrl(url, sameTab);
}
2021-10-13 13:31:01 +02:00
} else if (e.code === 'Escape') {
clearSearch();
}
2021-09-06 12:24:01 +02:00
};
return (
2021-10-13 13:31:01 +02:00
<div className={classes.SearchContainer}>
<input
ref={inputRef}
type="text"
className={classes.SearchBar}
onKeyUp={(e) => searchHandler(e)}
onDoubleClick={clearSearch}
2021-10-13 13:31:01 +02:00
/>
</div>
2021-09-06 12:24:01 +02:00
);
};
2021-09-06 12:24:01 +02:00
export default connect(null, { createNotification })(SearchBar);