Created
April 11, 2014 13:39
-
-
Save sorribas/10469758 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
/** @jsx React.DOM */ | |
var React = require('react') | |
module.exports = React.createClass({ displayName: 'SearchPopup', | |
propTypes: { | |
onSelect: React.PropTypes.func.isRequired, | |
items: React.PropTypes.arrayOf( | |
React.PropTypes.shape({ | |
columns: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, | |
}) | |
).isRequired, | |
title: React.PropTypes.string.isRequired, | |
}, | |
getInitialState: function() { | |
return { | |
query: '', | |
sortKey: 0, | |
sortAsscending: true | |
} | |
}, | |
sortById: function() { | |
this.setState({sortKey: 0, sortAsscending: !this.state.sortAsscending}); | |
}, | |
sortByTitle: function() { | |
this.setState({sortKey: 1, sortAsscending: !this.state.sortAsscending}); | |
}, | |
render: function() { | |
var query = this.state.query | |
var items = this.props.items.filter(function(item) { | |
return item.columns.some(function(col) { | |
return ~col.indexOf(query) | |
}) | |
}) | |
var sortKey = this.state.sortKey; | |
items = items.sort(function(a, b) { | |
if (!this.state.sortAsscending) {var tmp = a; a = b; b = tmp;} | |
if (isNaN(Number(a.columns[sortKey]))) return a.columns[sortKey].localeCompare(b.columns[sortKey]); | |
return Number(a.columns[sortKey]) - Number(b.columns[sortKey]); | |
}.bind(this)); | |
return ( | |
<div> | |
<h2>{this.props.title}</h2> | |
<input type="search" value={query} onChange={this.setQuery}/> | |
<div className="items"> | |
<h3> | |
<span onClick={this.sortById}><a href="javascript:void(0)">Id</a></span> | |
<span onClick={this.sortByTitle}><a href="javascript:void(0)">Title</a></span> | |
</h3> | |
{items.map(function(item) { | |
return ( | |
<div onClick={this.props.onSelect.bind(null, item)}> | |
{item.columns.map(function(column) { | |
return <span>{column}</span> | |
})} | |
</div> | |
) | |
}, this)} | |
</div> | |
</div> | |
) | |
}, | |
setQuery: function(event) { | |
var value = event.target.value | |
this.setState({ query: value }) | |
}, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment