emoji-mart-lazyload/src/components/search.js

84 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-05-31 18:39:30 +00:00
import React from 'react'
import lunr from 'lunr'
import data from '../../data'
export default class Search extends React.Component {
constructor(props) {
super(props)
this.buildIndex()
}
buildIndex() {
this.index = lunr(function() {
this.pipeline.reset()
2016-05-31 18:39:30 +00:00
this.field('short_name', { boost: 2 })
2016-07-07 21:12:45 +00:00
this.field('emoticons')
2016-05-31 18:39:30 +00:00
this.field('name')
this.ref('id')
2016-05-31 18:39:30 +00:00
})
for (let emoji in data.emojis) {
let emojiData = data.emojis[emoji],
2016-07-07 21:22:40 +00:00
{ short_name, name, emoticons } = emojiData
2016-05-31 18:39:30 +00:00
this.index.add({
id: short_name,
2016-07-07 21:22:40 +00:00
emoticons: emoticons,
short_name: this.tokenize(short_name),
name: this.tokenize(name),
})
2016-05-31 18:39:30 +00:00
}
}
tokenize (string) {
if (['-', '-1', '+', '+1'].indexOf(string) == 0) {
return string.split('')
}
2016-07-07 21:12:45 +00:00
if (/(:|;|=)-/.test(string)) {
return [string]
}
return string.split(/[-|_|\s]+/)
}
2016-05-31 18:39:30 +00:00
handleChange() {
var { input } = this.refs,
value = input.value,
results = null
if (value.length) {
results = this.index.search(this.tokenize(value)).map((result) =>
2016-05-31 18:39:30 +00:00
result.ref
)
}
this.props.onSearch(results)
}
clear() {
this.refs.input.value = ''
}
2016-05-31 18:39:30 +00:00
render() {
return <input
ref='input'
type='text'
onChange={this.handleChange.bind(this)}
placeholder='Search'
className='emoji-picker-search'
/>
}
}
Search.propTypes = {
onSearch: React.PropTypes.func,
}
Search.defaultProps = {
onSearch: (() => {}),
}