Created
April 11, 2014 13:50
-
-
Save mafintosh/10470492 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') | |
var lex = require('lexicographic-integer') | |
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: '', | |
index: 0, | |
direction: 1 | |
} | |
}, | |
render: function() { | |
var index = this.state.index | |
var query = this.state.query | |
var items = this.props.items.filter(function(item) { | |
return item.columns.some(function(col) { | |
return ~col.toLowerCase().indexOf(query.toLowerCase()) | |
}) | |
}) | |
var dir = this.state.direction; | |
var cmp = function(a, b) { | |
if (typeof a === 'number') a = lex.pack(a, 'hex'); | |
if (typeof b === 'number') b = lex.pack(b, 'hex'); | |
return a.toLowerCase().localeCompare(b.toLowerCase()); | |
}; | |
items.sort(function(a, b) { | |
return dir * cmp(a.columns[index],b.columns[index]); | |
}) | |
return ( | |
<div> | |
<h2>{this.props.title}</h2> | |
<input type="search" value={query} onChange={this.setQuery}/> | |
<div className="items"> | |
<h3> | |
<a href="javascript:void(0)" data-index="0" onClick={this.setSortProp}>Id</a> | |
<a href="javascript:void(0)" data-index="1" onClick={this.setSortProp}>Title</a> | |
</h3> | |
{items.map(function(item) { | |
return ( | |
<div onClick={this.props.onSelect.bind(null, item)}> | |
{item.columns.map(function(column) { | |
var i = column.toLowerCase().indexOf(query.toLowerCase()); | |
if (i === -1) return <span className="col">{column}</span> | |
return <span className="col">{column.slice(0, i)}<b className="highlight">{column.slice(i, i+query.length)}</b>{column.slice(i+query.length)}</span> | |
})} | |
</div> | |
) | |
}, this)} | |
</div> | |
</div> | |
) | |
}, | |
setSortProp: function(event) { | |
var index = Number(event.target.getAttribute('data-index')); | |
var dir = this.state.direction; | |
if (this.state.index === index) dir *= -1; | |
else dir = 1 | |
this.setState({ index: index, direction: dir }) | |
}, | |
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