1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-24 12:23:39 +02: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

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';
2020-10-06 20:28:38 +02:00
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-10-06 20:28:38 +02:00
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('');
2020-10-06 20:28:38 +02:00
const handleSearch = (newSearchQuery) => {
setSearchQuery(newSearchQuery);
const fuseSearchResult = fuseRef.current.search(newSearchQuery);
2020-10-06 20:28:38 +02:00
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,
});
2020-10-06 20:28:38 +02:00
}
}, [fuseSearchKeys, listToSearch]);
2020-10-06 20:28:38 +02:00
2021-04-01 20:44:42 +02:00
const previousListToSearch = usePrevious(listToSearch ?? []);
2020-10-06 20:28:38 +02:00
useEffect(() => {
2020-11-03 00:41:28 +01:00
if (
fuseRef.current &&
searchQuery &&
previousListToSearch !== listToSearch
) {
fuseRef.current.setCollection(listToSearch);
const fuseSearchResult = fuseRef.current.search(searchQuery);
onSearch({ searchQuery, results: fuseSearchResult });
2020-10-06 20:28:38 +02:00
}
}, [listToSearch, searchQuery, onSearch, previousListToSearch]);
2020-10-06 20:28:38 +02:00
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
/>
);
2020-10-06 20:28:38 +02:00
}
ListItemSearch.propTypes = {
onSearch: PropTypes.func,
error: PropTypes.string,
listToSearch: PropTypes.array.isRequired,
fuseSearchKeys: PropTypes.arrayOf(PropTypes.object).isRequired,
searchPlaceholderText: PropTypes.string,
defaultToAll: PropTypes.bool,
};