1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-01 21:57:06 +01:00
metamask-extension/ui/app/pages/swaps/searchable-item-list/list-item-search/list-item-search.component.js

87 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-10-06 20:28:38 +02:00
import React, { useState, useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import Fuse from 'fuse.js'
import InputAdornment from '@material-ui/core/InputAdornment'
import TextField from '../../../../components/ui/text-field'
import { usePrevious } from '../../../../hooks/usePrevious'
const renderAdornment = () => (
2020-11-03 00:41:28 +01:00
<InputAdornment position="start" style={{ marginRight: '12px' }}>
<img src="images/search.svg" width="17" height="17" alt="" />
2020-10-06 20:28:38 +02:00
</InputAdornment>
)
2020-11-03 00:41:28 +01:00
export default function ListItemSearch({
2020-10-06 20:28:38 +02:00
onSearch,
error,
listToSearch = [],
fuseSearchKeys,
searchPlaceholderText,
defaultToAll,
}) {
const fuseRef = useRef()
const [searchQuery, setSearchQuery] = useState('')
const handleSearch = (newSearchQuery) => {
setSearchQuery(newSearchQuery)
const fuseSearchResult = fuseRef.current.search(newSearchQuery)
onSearch({
searchQuery: newSearchQuery,
2020-11-03 00:41:28 +01:00
results:
defaultToAll && newSearchQuery === '' ? listToSearch : fuseSearchResult,
2020-10-06 20:28:38 +02:00
})
}
useEffect(() => {
if (!fuseRef.current) {
fuseRef.current = new Fuse(listToSearch, {
shouldSort: true,
threshold: 0.45,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: fuseSearchKeys,
})
}
}, [fuseSearchKeys, listToSearch])
const previousListToSearch = usePrevious(listToSearch) || []
useEffect(() => {
2020-11-03 00:41:28 +01:00
if (
fuseRef.current &&
searchQuery &&
previousListToSearch !== listToSearch
) {
2020-10-06 20:28:38 +02:00
fuseRef.current.setCollection(listToSearch)
const fuseSearchResult = fuseRef.current.search(searchQuery)
onSearch({ searchQuery, results: fuseSearchResult })
}
}, [listToSearch, searchQuery, onSearch, previousListToSearch])
return (
<TextField
data-testid="search-list-items"
className="searchable-item-list__search"
placeholder={searchPlaceholderText}
type="text"
value={searchQuery}
onChange={(e) => handleSearch(e.target.value)}
error={error}
fullWidth
startAdornment={renderAdornment()}
autoComplete="off"
autoFocus
/>
)
}
ListItemSearch.propTypes = {
onSearch: PropTypes.func,
error: PropTypes.string,
listToSearch: PropTypes.array.isRequired,
fuseSearchKeys: PropTypes.arrayOf(PropTypes.object).isRequired,
searchPlaceholderText: PropTypes.string,
defaultToAll: PropTypes.bool,
}