2017-09-19 14:47:10 +00:00
|
|
|
import Ember from 'ember';
|
|
|
|
|
|
|
|
const { Mixin, computed, get } = Ember;
|
|
|
|
|
|
|
|
/**
|
|
|
|
Searchable mixin
|
|
|
|
|
|
|
|
Simple search filtering behavior for a list of objects.
|
|
|
|
|
|
|
|
Properties to override:
|
|
|
|
- searchTerm: the string to use as a query
|
|
|
|
- searchProps: the props on each object to search
|
|
|
|
- listToSearch: the list of objects to search
|
|
|
|
|
|
|
|
Properties provided:
|
2017-10-18 19:52:24 +00:00
|
|
|
- listSearched: a subset of listToSearch of items that meet the search criteria
|
2017-09-19 14:47:10 +00:00
|
|
|
*/
|
|
|
|
export default Mixin.create({
|
|
|
|
searchTerm: '',
|
|
|
|
listToSearch: computed(() => []),
|
|
|
|
searchProps: null,
|
|
|
|
|
2017-10-19 02:45:12 +00:00
|
|
|
listSearched: computed('searchTerm', 'listToSearch.[]', 'searchProps.[]', function() {
|
|
|
|
const searchTerm = this.get('searchTerm');
|
2017-09-19 14:47:10 +00:00
|
|
|
if (searchTerm && searchTerm.length) {
|
2017-10-19 02:45:12 +00:00
|
|
|
return regexSearch(searchTerm, this.get('listToSearch'), this.get('searchProps'));
|
2017-09-19 14:47:10 +00:00
|
|
|
}
|
|
|
|
return this.get('listToSearch');
|
|
|
|
}),
|
|
|
|
});
|
|
|
|
|
2017-10-19 02:45:12 +00:00
|
|
|
function regexSearch(term, list, keys) {
|
2017-10-18 19:52:24 +00:00
|
|
|
if (term.length) {
|
2017-09-19 14:47:10 +00:00
|
|
|
try {
|
2017-10-18 19:52:24 +00:00
|
|
|
const regex = new RegExp(term, 'i');
|
2017-09-19 14:47:10 +00:00
|
|
|
// Test the value of each key for each object against the regex
|
|
|
|
// All that match are returned.
|
|
|
|
return list.filter(item => keys.some(key => regex.test(get(item, key))));
|
|
|
|
} catch (e) {
|
|
|
|
// Swallow the error; most likely due to an eager search of an incomplete regex
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|