blob: 881a9444a39c3b3c3e6e65a21ad85f3b2f05a9b6 [file] [log] [blame]
bigbiffd006b302015-03-06 18:36:03 -05001;(function(window,document,undefined){
2 'use strict';
3
4 var Searcher = require('./Searcher');
5 var Templater = require('./Templater');
6 var Store = require('./Store');
7 var JSONLoader = require('./JSONLoader');
8
9 var searcher = new Searcher();
10 var templater = new Templater();
11 var store = new Store();
12 var jsonLoader = new JSONLoader();
13
14
15 window.SimpleJekyllSearch = new SimpleJekyllSearch();
16 function SimpleJekyllSearch(){
17 var self = this;
18
19 var requiredOptions = [
20 'searchInput',
21 'resultsContainer',
22 'dataSource',
23 ];
24 var opt = {
25 searchInput: null,
26 resultsContainer: null,
27 dataSource: [],
28 searchResultTemplate: '<li><a href="{url}" title="{desc}">{title}</a></li>',
29 noResultsText: 'No results found',
30 limit: 10,
31 fuzzy: false,
32 };
33
34 function initWithJSON(json){
35 store.put(opt.dataSource);
36 registerInput();
37 }
38
39 function initWithURL(url){
40 jsonLoader.load(url, function gotJSON(err,json){
41 if( !err ) {
42 store.put(json);
43 registerInput();
44 }else{
45 throwError('failed to get JSON (' + url + ')');
46 }
47 });
48 }
49
50 self.init = function(_opt){
51 validateOptions(_opt);
52 assignOptions(_opt);
53 if( isJSON(opt.dataSource) ){
54 initWithJSON(opt.dataSource);
55 }else{
56 initWithURL(opt.dataSource);
57 }
58 };
59
60
61 function throwError(message){ throw new Error('SimpleJekyllSearch --- '+ message); }
62
63 function validateOptions(_opt){
64 for(var i = 0; i < requiredOptions.length; i++){
65 var req = requiredOptions[i];
66 if( !_opt[req] )
67 throwError('You must specify a ' + req);
68 }
69 }
70
71 function assignOptions(_opt){
72 for(var option in opt)
73 opt[option] = _opt[option] || opt[option];
74 }
75
76 function isJSON(json){
77 try{
78 return json instanceof Object && JSON.parse(JSON.stringify(json));
79 }catch(e){
80 return false;
81 }
82 }
83
84 function emptyResultsContainer(){
85 opt.resultsContainer.innerHTML = '';
86 }
87
88 function appendToResultsContainer(text){
89 opt.resultsContainer.innerHTML += text;
90 }
91
92 function registerInput(){
93 opt.searchInput.addEventListener('keyup', function(e){
94 if( e.target.value.length == 0 ){
95 emptyResultsContainer();
96 return;
97 }
98 render( searcher.search(store, e.target.value) );
99 });
100 }
101
102 function render(results){
103 emptyResultsContainer();
104 if( results.length == 0 ){
105 return appendToResultsContainer(opt.noResultsText);
106 }
107 for (var i = 0; i < results.length; i++) {
108 appendToResultsContainer( templater.render(opt.searchResultTemplate, results[i]) );
109 };
110 }
111
112 };
113})(window,document);