Vulcan/packages/vulcan-base-components/lib/common/SearchForm.jsx

76 lines
1.9 KiB
React
Raw Normal View History

2017-05-19 22:03:03 +09:00
import { registerComponent, Components } from 'meteor/vulcan:core';
2016-03-22 11:04:59 +09:00
import React, { PropTypes, Component } from 'react';
2016-06-09 17:42:20 +09:00
import { intlShape } from 'react-intl';
2016-03-22 11:04:59 +09:00
import Formsy from 'formsy-react';
import FRC from 'formsy-react-components';
2017-05-19 22:03:03 +09:00
import { withRouter, Link } from 'react-router'
2016-03-22 11:04:59 +09:00
const Input = FRC.Input;
// see: http://stackoverflow.com/questions/1909441/jquery-keyup-delay
const delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
class SearchForm extends Component{
2016-06-14 10:01:44 +09:00
constructor(props) {
super(props);
2016-03-22 11:04:59 +09:00
this.search = this.search.bind(this);
2016-06-14 10:01:44 +09:00
this.state = {
search: props.router.location.query.query || ''
}
}
2017-05-19 22:03:03 +09:00
// note: why do we need this?
2016-06-14 10:01:44 +09:00
componentWillReceiveProps(nextProps) {
this.setState({
search: this.props.router.location.query.query || ''
});
2016-03-22 11:04:59 +09:00
}
search(data) {
2016-06-14 10:01:44 +09:00
const router = this.props.router;
2017-05-19 22:03:03 +09:00
const routerQuery = _.clone(router.location.query);
delete routerQuery.query;
const query = data.searchQuery === '' ? routerQuery : {...routerQuery, query: data.searchQuery};
2016-06-14 10:01:44 +09:00
delay(() => {
2016-06-14 10:17:11 +09:00
router.push({pathname: "/", query: query});
2016-03-22 11:04:59 +09:00
}, 700 );
}
render() {
2017-05-19 22:03:03 +09:00
const resetQuery = _.clone(this.props.location.query);
delete resetQuery.query;
2016-03-22 11:04:59 +09:00
return (
<div className="search-form">
<Formsy.Form onChange={this.search}>
<Input
name="searchQuery"
2016-06-14 10:01:44 +09:00
value={this.state.search}
2016-06-09 17:42:20 +09:00
placeholder={this.context.intl.formatMessage({id: "posts.search"})}
2016-03-22 11:04:59 +09:00
type="text"
2016-03-30 10:06:12 +09:00
layout="elementOnly"
2016-03-22 11:04:59 +09:00
/>
2017-05-19 22:03:03 +09:00
{this.state.search !== '' ? <Link className="search-form-reset" to={{pathname: '/', query: resetQuery}}><Components.Icon name="close" /></Link> : null}
2016-03-22 11:04:59 +09:00
</Formsy.Form>
</div>
)
}
}
SearchForm.contextTypes = {
2016-06-09 17:42:20 +09:00
intl: intlShape
2016-11-15 18:33:16 +01:00
};
registerComponent('SearchForm', SearchForm, withRouter);