|  | 
|  | 1 | +import React, { Component } from 'react'; | 
|  | 2 | +import Autosuggest from '../../src/Autosuggest'; | 
|  | 3 | +import { escapeRegexCharacters } from '../../demo/src/components/utils/utils'; | 
|  | 4 | +import languages from '../plain-list/languages'; | 
|  | 5 | +import sinon from 'sinon'; | 
|  | 6 | +import { addEvent } from '../helpers'; | 
|  | 7 | + | 
|  | 8 | +const getMatchingLanguages = (value) => { | 
|  | 9 | +  const escapedValue = escapeRegexCharacters(value.trim()); | 
|  | 10 | +  const regex = new RegExp('^' + escapedValue, 'i'); | 
|  | 11 | + | 
|  | 12 | +  return languages.filter((language) => regex.test(language.name)); | 
|  | 13 | +}; | 
|  | 14 | + | 
|  | 15 | +let app = null; | 
|  | 16 | + | 
|  | 17 | +export const getSuggestionValue = (suggestion) => suggestion.name; | 
|  | 18 | + | 
|  | 19 | +export const renderSuggestion = (suggestion) => <span>{suggestion.name}</span>; | 
|  | 20 | + | 
|  | 21 | +export const onChange = sinon.spy((event, { newValue }) => { | 
|  | 22 | +  addEvent('onChange'); | 
|  | 23 | + | 
|  | 24 | +  app.setState({ | 
|  | 25 | +    value: newValue, | 
|  | 26 | +  }); | 
|  | 27 | +}); | 
|  | 28 | + | 
|  | 29 | +export const onSuggestionsFetchRequested = ({ value }) => { | 
|  | 30 | +  app.setState({ | 
|  | 31 | +    suggestions: getMatchingLanguages(value), | 
|  | 32 | +  }); | 
|  | 33 | +}; | 
|  | 34 | + | 
|  | 35 | +export const onSuggestionsClearRequested = () => { | 
|  | 36 | +  app.setState({ | 
|  | 37 | +    suggestions: [], | 
|  | 38 | +  }); | 
|  | 39 | +}; | 
|  | 40 | + | 
|  | 41 | +export const shouldKeepSuggestionsOnSelect = (suggestion) => { | 
|  | 42 | +  return suggestion.name.toLowerCase().startsWith('clo'); | 
|  | 43 | +}; | 
|  | 44 | + | 
|  | 45 | +export default class AutosuggestApp extends Component { | 
|  | 46 | +  constructor() { | 
|  | 47 | +    super(); | 
|  | 48 | + | 
|  | 49 | +    app = this; | 
|  | 50 | + | 
|  | 51 | +    this.state = { | 
|  | 52 | +      value: '', | 
|  | 53 | +      suggestions: [], | 
|  | 54 | +    }; | 
|  | 55 | +  } | 
|  | 56 | + | 
|  | 57 | +  render() { | 
|  | 58 | +    const { value, suggestions } = this.state; | 
|  | 59 | +    const inputProps = { | 
|  | 60 | +      value, | 
|  | 61 | +      onChange, | 
|  | 62 | +    }; | 
|  | 63 | + | 
|  | 64 | +    return ( | 
|  | 65 | +      <Autosuggest | 
|  | 66 | +        suggestions={suggestions.slice()} | 
|  | 67 | +        onSuggestionsFetchRequested={onSuggestionsFetchRequested} | 
|  | 68 | +        onSuggestionsClearRequested={onSuggestionsClearRequested} | 
|  | 69 | +        getSuggestionValue={getSuggestionValue} | 
|  | 70 | +        renderSuggestion={renderSuggestion} | 
|  | 71 | +        inputProps={inputProps} | 
|  | 72 | +        shouldKeepSuggestionsOnSelect={shouldKeepSuggestionsOnSelect} | 
|  | 73 | +      /> | 
|  | 74 | +    ); | 
|  | 75 | +  } | 
|  | 76 | +} | 
0 commit comments