Created
July 4, 2016 09:35
-
-
Save momolog/c6cb194bfba11758b3210afda718782f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{div, h1, h2, img, form, input} = React.DOM | |
@SearchBox = React.createClass | |
render: -> | |
div className: 'searchbox-container', | |
React.createElement Form, searchText: this.state.searchText, onSearchChange: this.searchChanged, onFocus: this.onFocus, onBlur: this.onBlur | |
React.createElement ResultList, data: this.state.data, category: this.state.category, visible: (this.state.hasResults && this.state.focus) | |
searchChanged: (val) -> | |
clearTimeout(this.searchTimeout) | |
self = this | |
self.setState({searchText: val}) | |
if val.length | |
self.searchTimeout = setTimeout (-> self.doSearch(val)), 500 | |
else | |
self.setState self.getInitialState() | |
onFocus: -> this.setState focus: true | |
onBlur: -> this.setState focus: false | |
doSearch: (val) -> | |
return if this.state.searchText.length == 0 | |
self = this | |
$.ajax self.props.url, { data: {q: val}, dataType: 'json', success: (data) -> self.setState data: data, hasResults: data.length > 0 } | |
getInitialState: -> {searchText: '', data: [], category: '', hasResults: false, hasFocus: false} | |
@Form = React.createClass | |
render: -> | |
form className: 'searchbox-form', | |
`<svg className='icon svg-magnifier' id='magnifier'> | |
<use xmlnsXlink='http://www.w3.org/1999/xlink' xlinkHref='#svg-magnifier' /> | |
</svg>` | |
input value: this.props.searchText, ref: 'searchTextInput', onChange: this.handleChange, onBlur: this.props.onBlur, onFocus: this.props.onFocus, | |
handleChange: -> this.props.onSearchChange(this.refs.searchTextInput.value) | |
@ResultList = React.createClass | |
render: -> | |
div className: this.getClass(), this.props.data.map (category) -> | |
div className: 'searchbox-category', key: "searchbox-category-#{category.title}", | |
div className: 'searchbox-category-header', category.title | |
div className: 'searchbox-category-results', category.results.map (r) -> | |
React.createElement ResultItem, {href: r[0], text: r[1], image: r[2], key: r[0]} | |
getClass: -> | |
"searchbox-resultlist #{if this.props.visible then 'visible' else 'invisible'}" | |
@ResultItem = React.createClass | |
render: -> | |
div className: 'searchbox-resultitem', onClick: this.onClick, | |
div className: 'searchbox-resultitem-image', img src: this.props.image | |
div className: 'searchbox-resultitem-text', this.props.text | |
onClick: -> window.location.href = this.props.href |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment