import React, { useReducer, useEffect, useRef, KeyboardEvent, SyntheticEvent } from 'react'; import snakecase from 'lodash.snakecase'; import mapkeys from 'lodash.mapkeys'; import {useDebounce} from 'use-debounce'; import useOnClickOutside from 'use-onclickoutside'; import classNames from 'classnames'; import { TSearchResultGroup, TSearchResult, getFlatResults, titleize } from 'shared/utils/search'; import {SegmentEvents} from 'moda-analytics'; import SearchIcon from '@moda/icons/search-24'; import ExitIcon from '@moda/icons/exit-16'; import {Theme} from './index'; import './search_bar.scss'; export interface Props { theme?: Theme; placeholder?: string; placeholderAlignment?: 'center' | 'left'; defaultResults?: TSearchResultGroup[]; getResults(query: string): Promise; onSubmit(query: string, result?: TSearchResult): void; searchSuggestionMessagingFlag?: string; doubleTapInput: boolean; } interface TState { query: string; results: TSearchResultGroup[]; showResults: boolean; selectedResultIndex: number; } type TAction = | {type: 'CHANGE_QUERY'; payload: string} | {type: 'RECEIVE_RESULTS'; payload: TSearchResultGroup[]} | {type: 'SELECT_NEXT_RESULT'} | {type: 'SELECT_PREVIOUS_RESULT'} | {type: 'SHOW_RESULTS'} | {type: 'CLEAR_SELECTED_RESULT'} | {type: 'CLEAR_ALL'}; const initialState: TState = { query: '', results: [], showResults: false, selectedResultIndex: -1 }; interface SearchBarInteractionEvent { target: string; query: string; previousSearchText: string; } const getSearchSuggestionString = ( searchString: string, searchSuggestionMessagingFlag: string ) => { if (searchSuggestionMessagingFlag === 'on') { const words = searchString.split(' ').map(word => word.match(/.{1,27}/g)); return [].concat(...words).join(' '); } return 'No Suggestions Found'; }; const segmentEventToSnakecase = (event: SearchBarInteractionEvent) => mapkeys(event, (_, key) => snakecase(key)); const trackSearchBarClick = () => { SegmentEvents && SegmentEvents.onSearchBarClick({target: window.location.href}); }; const trackSearchInteraction = (previousValue: string, newValue: string) => { SegmentEvents && SegmentEvents.onSearchBarInteraction( segmentEventToSnakecase({ target: window.location.href, query: newValue.toLowerCase(), previousSearchText: previousValue.toLowerCase() }) ); }; const reducer = (state: TState, action: TAction) => { switch (action.type) { case 'CHANGE_QUERY': return { ...state, query: action.payload, showResults: action.payload ? true : state.showResults }; case 'RECEIVE_RESULTS': return { ...state, results: action.payload, selectedResultIndex: -1 }; case 'SELECT_NEXT_RESULT': return { ...state, selectedResultIndex: getFlatResults(state.results)[ state.selectedResultIndex + 1 ] ? state.selectedResultIndex + 1 : state.selectedResultIndex }; case 'SELECT_PREVIOUS_RESULT': return { ...state, selectedResultIndex: getFlatResults(state.results)[ state.selectedResultIndex - 1 ] ? state.selectedResultIndex - 1 : state.selectedResultIndex }; case 'SHOW_RESULTS': return { ...state, showResults: true }; case 'CLEAR_SELECTED_RESULT': return { ...state, selectedResultIndex: -1 }; case 'CLEAR_ALL': return initialState; default: throw new Error('invalid action'); } }; const SearchBar: React.FC = ({ theme = 'white', placeholder = 'Enter Search Term Here', placeholderAlignment = 'left', defaultResults = [], searchSuggestionMessagingFlag = 'off', doubleTapInput = false, getResults, onSubmit }: Props) => { const [ {query, results, showResults, selectedResultIndex}, dispatch ] = useReducer(reducer, initialState); const [debouncedQuery] = useDebounce(query, 100); const containerRef = useRef(null); const lastRequest = useRef(null); const flatResults = getFlatResults(results); useEffect(() => { let request: Promise | null = null; const fetchResults = async () => { try { const results = await (debouncedQuery ? getResults(debouncedQuery) : Promise.resolve(defaultResults)); // make sure this is the last request, avoid setting results from an older request if (lastRequest.current === request) { dispatch({type: 'RECEIVE_RESULTS', payload: results}); } } catch (error) { if (lastRequest.current === request) { dispatch({type: 'RECEIVE_RESULTS', payload: []}); } } }; request = fetchResults(); lastRequest.current = request; }, [debouncedQuery, showResults, defaultResults, getResults]); useOnClickOutside(containerRef, () => dispatch({type: 'CLEAR_ALL'})); const onKeyUp = (event: KeyboardEvent) => { if (event.keyCode == 38) { dispatch({type: 'SELECT_PREVIOUS_RESULT'}); } else if (event.keyCode == 40) { dispatch({type: 'SELECT_NEXT_RESULT'}); } else { dispatch({type: 'CLEAR_SELECTED_RESULT'}); } }; const handleOverlayClick = () => { dispatch({type: 'SHOW_RESULTS'}); }; const handleInputFocus = () => { if (doubleTapInput) return; dispatch({type: 'SHOW_RESULTS'}); }; const onFormSubmit = (event: SyntheticEvent) => { event.preventDefault(); onSubmit( query, flatResults.length === 1 ? flatResults[0] : flatResults[selectedResultIndex] ); dispatch({type: 'CLEAR_ALL'}); }; return (
trackSearchBarClick()} onChange={event => { trackSearchInteraction(query, event.target.value); dispatch({type: 'CHANGE_QUERY', payload: event.target.value}); }} onKeyUp={onKeyUp} onFocus={handleInputFocus} /> {showResults && results.length > 0 && (
dispatch({type: 'CLEAR_ALL'})} >
)}
{showResults && results.length > 0 && (
{results.map( result => result.results.length > 0 && ( ) )} {results.every(result => result.results.length === 0) && (
{getSearchSuggestionString( `Search for ${query}`, searchSuggestionMessagingFlag )}
)}
)}
); }; export default SearchBar;