@kiwicom/smart-faq
Version:
Smart FAQ
85 lines (75 loc) • 2.44 kB
JavaScript
// @flow
import * as React from 'react';
import { Search } from '@kiwicom/orbit-components/lib/icons';
import { Consumer as IntlConsumer } from '@kiwicom/nitro/lib/services/intl/context';
import { withRouter } from 'react-router';
import Input from '../../SmartFAQ/common/Input';
import { SearchState } from '../../SmartFAQ/context/SearchState';
import type { SearchStateType } from '../../SmartFAQ/context/SearchState';
import { simpleTracker } from '../../shared/helpers/analytics/trackers';
import { debounce } from '../../SmartFAQ/helpers/functionUtils';
import { track } from '../../shared/cuckoo/tracker';
type Props = {|
history: {
push: string => void,
location: { pathname: string },
},
autofocus: boolean,
|};
const logSearchQuery = debounce(query => {
simpleTracker('smartFAQBookingOverview', {
action: 'search',
searchedText: query.toLowerCase(),
});
track('FAQs', 'search', { searchedText: query.toLowerCase() });
});
const SearchBar = ({ history, autofocus }: Props) => (
<SearchState.Consumer>
{({
searchText,
changeSearchText,
incrementQueriesCount,
resetQueriesCount,
}: SearchStateType) => {
const isSearching = searchText.length > 0;
const onSearchCancel = () => {
changeSearchText('');
resetQueriesCount();
};
const onSearchChange = (e: SyntheticInputEvent<HTMLInputElement>) => {
const query = e.target.value;
if (query.length) {
incrementQueriesCount();
changeSearchText(query);
if (query.length >= 2) {
logSearchQuery(query);
}
} else {
onSearchCancel();
}
};
return (
<IntlConsumer>
{intl => {
const placeholder = intl.translate(
__('smartfaq.search_input.placeholder'),
);
return (
<Input
value={searchText}
onChange={onSearchChange}
placeholder={placeholder}
icon={<Search customColor="#bac7d5" />}
onReset={isSearching ? onSearchCancel : undefined}
onFocus={() => history.push('/faq')}
dataCy="input-staticFAQ"
autoFocus={autofocus}
/>
);
}}
</IntlConsumer>
);
}}
</SearchState.Consumer>
);
export default withRouter(SearchBar);