p5.js-web-editor/client/modules/IDE/components/Searchbar/Searchbar.jsx

85 lines
2.1 KiB
React
Raw Normal View History

import PropTypes from 'prop-types';
import React from 'react';
import { throttle } from 'lodash';
2020-04-30 00:34:37 +02:00
import SearchIcon from '../../../../images/magnifyingglass.svg';
class Searchbar extends React.Component {
constructor(props) {
super(props);
this.state = {
searchValue: this.props.searchTerm
};
this.throttledSearchChange = throttle(this.searchChange, 500);
}
componentWillUnmount() {
this.props.resetSearchTerm();
}
handleResetSearch = () => {
this.setState({ searchValue: '' }, () => {
this.props.resetSearchTerm();
});
}
handleSearchEnter = (e) => {
if (e.key === 'Enter') {
2020-04-06 05:51:09 +02:00
this.searchChange();
}
}
2020-04-06 05:51:09 +02:00
searchChange = () => {
if (this.state.searchValue.trim().length === 0) return;
this.props.setSearchTerm(this.state.searchValue.trim());
};
handleSearchChange = (e) => {
2020-07-27 20:17:51 +02:00
if (e.target.value === '') {
// Manually reset the searchValue if the search field becomes empty.
this.handleResetSearch();
return;
}
this.setState({ searchValue: e.target.value }, () => {
this.throttledSearchChange(this.state.searchValue);
});
}
render() {
const { searchValue } = this.state;
return (
<div className={`searchbar ${searchValue === '' ? 'searchbar--is-empty' : ''}`}>
2020-02-25 18:52:52 +01:00
<div className="searchbar__button">
<SearchIcon className="searchbar__icon" focusable="false" aria-hidden="true" />
2020-02-25 18:52:52 +01:00
</div>
<input
className="searchbar__input"
type="text"
value={searchValue}
placeholder={this.props.searchLabel}
onChange={this.handleSearchChange}
onKeyUp={this.handleSearchEnter}
/>
<button
className="searchbar__clear-button"
onClick={this.handleResetSearch}
>clear
</button>
</div>
);
}
}
Searchbar.propTypes = {
searchTerm: PropTypes.string.isRequired,
setSearchTerm: PropTypes.func.isRequired,
resetSearchTerm: PropTypes.func.isRequired,
searchLabel: PropTypes.string,
};
Searchbar.defaultProps = {
searchLabel: 'Search sketches...',
};
export default Searchbar;