2020-09-15 15:01:07 +02:00
|
|
|
import * as React from 'react';
|
|
|
|
import { useState, useCallback, useEffect } from 'react';
|
|
|
|
import CommandService from 'lib/services/CommandService';
|
|
|
|
import useSearch from './hooks/useSearch';
|
|
|
|
import { Root, SearchInput, SearchButton, SearchButtonIcon } from './styles';
|
|
|
|
const { connect } = require('react-redux');
|
|
|
|
|
|
|
|
const { _ } = require('lib/locale.js');
|
|
|
|
|
|
|
|
interface Props {
|
|
|
|
inputRef?: any,
|
|
|
|
notesParentType: string,
|
2020-09-29 13:31:19 +02:00
|
|
|
dispatch?: Function,
|
2020-09-15 15:01:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function SearchBar(props:Props) {
|
|
|
|
const [query, setQuery] = useState('');
|
|
|
|
const iconName = !query ? CommandService.instance().iconName('search') : 'fa fa-times';
|
|
|
|
|
2020-09-29 13:31:19 +02:00
|
|
|
function onChange(event:any) {
|
2020-09-15 15:01:07 +02:00
|
|
|
setQuery(event.currentTarget.value);
|
2020-09-29 13:31:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function onFocus() {
|
|
|
|
props.dispatch({
|
|
|
|
type: 'FOCUS_SET',
|
|
|
|
field: 'globalSearch',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function onBlur() {
|
|
|
|
// Do it after a delay so that the "Clear" button
|
|
|
|
// can be clicked on (otherwise the field loses focus
|
|
|
|
// and is resized before the click event has been processed)
|
|
|
|
setTimeout(() => {
|
|
|
|
props.dispatch({
|
|
|
|
type: 'FOCUS_CLEAR',
|
|
|
|
field: 'globalSearch',
|
|
|
|
});
|
|
|
|
}, 300);
|
|
|
|
}
|
|
|
|
|
|
|
|
function onKeyDown(event:any) {
|
|
|
|
if (event.key === 'Escape') {
|
|
|
|
setQuery('');
|
|
|
|
if (document.activeElement) (document.activeElement as any).blur();
|
|
|
|
}
|
|
|
|
}
|
2020-09-15 15:01:07 +02:00
|
|
|
|
|
|
|
const onSearchButtonClick = useCallback(() => {
|
|
|
|
setQuery('');
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
useSearch(query);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (props.notesParentType !== 'Search') {
|
|
|
|
setQuery('');
|
|
|
|
}
|
|
|
|
}, [props.notesParentType]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<Root>
|
2020-09-29 13:31:19 +02:00
|
|
|
<SearchInput
|
|
|
|
ref={props.inputRef}
|
|
|
|
value={query}
|
|
|
|
type="text"
|
|
|
|
placeholder={_('Search...')}
|
|
|
|
onChange={onChange}
|
|
|
|
onFocus={onFocus}
|
|
|
|
onBlur={onBlur}
|
|
|
|
onKeyDown={onKeyDown}
|
|
|
|
/>
|
2020-09-15 15:01:07 +02:00
|
|
|
<SearchButton onClick={onSearchButtonClick}>
|
|
|
|
<SearchButtonIcon className={iconName}/>
|
|
|
|
</SearchButton>
|
|
|
|
</Root>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const mapStateToProps = (state:any) => {
|
|
|
|
return {
|
|
|
|
notesParentType: state.notesParentType,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default connect(mapStateToProps)(SearchBar);
|