Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.72 KB | None | 0 0
  1. import React, { Component } from 'react'
  2. import { View, Text, TextInput, FlatList, Image, TouchableOpacity } from 'react-native'
  3. import { inject, observer } from 'mobx-react/native'
  4. import { Button } from '../../components'
  5. import Style from './style'
  6. import I18n from '../../i18n'
  7. import Icon from 'react-native-vector-icons/MaterialIcons'
  8. import Api from '../../utils/Api'
  9. import _ from 'lodash'
  10.  
  11. let mounted = false
  12. @inject('UserStore', 'NavigationStore')
  13. @observer
  14. class SearchProducts extends Component {
  15. constructor(props) {
  16. super(props)
  17. this.state = {
  18. searchAutoComplete: [],
  19. showAutoComplete: false,
  20. currentSearch: '',
  21. searchTimeoutId: null,
  22. }
  23. this.autoCompleteTimeout = null
  24. this.storedResults = []
  25. }
  26.  
  27. componentWillMount() {
  28. mounted = true
  29. }
  30. componentWillUnmount() {
  31. mounted = false
  32. clearTimeout(this.autoCompleteTimeout)
  33. }
  34. _renderCategory = ({ item }) => {
  35. return (
  36. <View style={Style.featuredView}>
  37. <Image source={item.image} style={Style.featuredImage} />
  38. <Text style={{ textAlign: 'center', color: '#9B999A' }}>{item.title}</Text>
  39. </View>
  40. )
  41. }
  42.  
  43. _renderSuggestion = ({ item, index }) => {
  44. const splittedName = item.split(' ')
  45. let splittedSearch = this.state.currentSearch.toUpperCase().split(' ')
  46. splittedSearch = splittedSearch.map(x => x.trim()).filter(x => x.length > 1)
  47. let suggestion = []
  48. if (splittedSearch.length == 0) {
  49. suggestion = splittedName.map((word, index) => <Text key={index}>{word} </Text>)
  50. } else {
  51. let highlightedWords = []
  52. splittedName.forEach((word, index) =>
  53. splittedSearch.forEach(wordFromSearch => {
  54. const currentWord = word.toUpperCase()
  55. const isAlreadyHighlighted = highlightedWords.includes(currentWord)
  56. if ((currentWord.includes(wordFromSearch.toUpperCase()) && this.state.currentSearch.length > 0) || isAlreadyHighlighted) {
  57. let v = (
  58. <Text key={index} style={{ color: '#2eb872' }}>
  59. {word}{' '}
  60. </Text>
  61. )
  62. if (!isAlreadyHighlighted) {
  63. highlightedWords.push(currentWord)
  64. }
  65. suggestion[index] = v
  66. } else {
  67. let v = <Text key={index}>{word} </Text>
  68. suggestion[index] = v
  69. }
  70. })
  71. )
  72. }
  73.  
  74. return (
  75. <TouchableOpacity
  76. style={Style.suggestionView}
  77. onPress={() => {
  78. this.props.UserStore.addRecentSearch(item)
  79. this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: item } })
  80. this.autoCompleteTimeout = setTimeout(() => {
  81. if (mounted) this.setState({ showAutoComplete: false })
  82. }, 400)
  83. }}
  84. >
  85. <Icon name='search' size={20} style={{}} />
  86. <Text style={{ marginLeft: 20, textAlign: 'left', color: '#9B999A' }}>{suggestion}</Text>
  87. </TouchableOpacity>
  88. )
  89. }
  90.  
  91. getSuggestions = async currentSearch => {
  92. try {
  93. const response = await Api.serachOutoCompleate(currentSearch)
  94. let searchAutoComplete = response.suggestions.products.map(product => product.product_title)
  95. response.suggestions.categories.forEach(categories => searchAutoComplete.push(categories))
  96. response.suggestions.warehouses.forEach(warehouse => searchAutoComplete.push(warehouse.warehouse_name))
  97. response.suggestions.upcs.forEach(upcs => searchAutoComplete.push(upcs.product_title))
  98. response.suggestions.tags.forEach(tags => searchAutoComplete.push(tags.product_title))
  99. this.storedResults[currentSearch] = searchAutoComplete
  100. if (mounted && currentSearch && searchAutoComplete) this.setState({ currentSearch: currentSearch, searchAutoComplete: searchAutoComplete })
  101. else this.setState({ currentSearch: currentSearch })
  102. } catch (error) {
  103. console.log(error)
  104. }
  105. }
  106.  
  107. _onSearchChange = _.debounce(currentSearch => {
  108. if (currentSearch === '') {
  109. this.setState({ filter: [], currentSearch })
  110. } else {
  111. if (this.storedResults[currentSearch]) {
  112. this.setState({ currentSearch })
  113. let searchAutoComplete = this.storedResults[currentSearch]
  114. if (mounted && currentSearch && searchAutoComplete) this.setState({ searchAutoComplete })
  115. } else {
  116. this.getSuggestions(currentSearch)
  117. }
  118. }
  119. }, 250)
  120.  
  121. render() {
  122. I18n.locale = this.props.UserStore.user.lang
  123. const recent = this.props.UserStore.RecentSearches
  124. return (
  125. <View style={Style.container}>
  126. <View style={Style.search_container}>
  127. <TextInput
  128. style={Style.search_input}
  129. underlineColorAndroid='transparent'
  130. placeholder={I18n.t('search_products')}
  131. returnKeyType='search'
  132. autoCorrect={false}
  133. onChangeText={this._onSearchChange}
  134. onFocus={() => this.setState({ showAutoComplete: true })}
  135. onSubmitEditing={event => {
  136. if (event.nativeEvent.text.length) this.props.UserStore.addRecentSearch(event.nativeEvent.text)
  137. this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: event.nativeEvent.text } })
  138. }}
  139. onKeyPress={() => this.suggestionTimeout && clearTimeout(this.suggestionTimeout)}
  140. blurOnSubmit
  141. />
  142. </View>
  143. {this.state.currentSearch.length > 0 && this.state.showAutoComplete && this.state.searchAutoComplete.length > 0 ? (
  144. <View style={{ paddingVertical: 10 }}>
  145. <FlatList initialNumToRender={20} data={this.state.searchAutoComplete} keyExtractor={(item, index) => item.toString()} renderItem={this._renderSuggestion} keyboardShouldPersistTaps='always' />
  146. </View>
  147. ) : (
  148. <View>
  149. {recent.length > 0 ? (
  150. <View>
  151. <View style={Style.whiteBorder} />
  152. <View style={Style.searchHistory}>
  153. <Text style={Style.searchHistory_header}>{I18n.t('recent_searches')}</Text>
  154. {recent.map((title, index) => (
  155. <Button
  156. key={index}
  157. style={Style.recentSearch}
  158. onPress={() => {
  159. this.props.UserStore.addRecentSearch(title)
  160. this.props.NavigationStore.navigate({ routeName: 'SearchResult', params: { search: title } })
  161. }}
  162. >
  163. <Icon name='schedule' style={Style.recentSearchIcon} />
  164. <Text style={Style.recentSearchText}>{title}</Text>
  165. </Button>
  166. ))}
  167. </View>
  168. </View>
  169. ) : null}
  170. </View>
  171. )}
  172. </View>
  173. )
  174. }
  175. }
  176.  
  177. export default SearchProducts
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement