forked from laktek/jQuery-Smart-Auto-Complete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.smart_autocomplete.js
635 lines (505 loc) · 24 KB
/
jquery.smart_autocomplete.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/**
* Smart Auto Complete plugin
*
* Copyright (c) 2011 Lakshan Perera (laktek.com)
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
*
*/
/*
Requirements: jQuery 1.5 or above
Usage:
$(target).smartAutoComplete({options})
Options:
minCharLimit: (integer) minimum characters user have to type before invoking the autocomplete (default: 1)
maxCharLimit: (integer) maximum characters user can type while invoking the autocomplete (default: null (unlimited))
maxResults: (integer) maximum number of results to return (default: null (unlimited))
delay: (integer) delay before autocomplete starts (default: 0)
disabled: (boolean) whether autocomplete disabled on the field (default: false)
forceSelect: (boolean) If set to true, field will be always filled with best matching result, without leaving the custom input.
Better to enable this option, if you want autocomplete field to behave similar to a HTML select field. (Check Example 2 in the demo)
(default: false)
typeAhead: (boolean) If set to true, it will offer the best matching result in grey within the field; that can be auto-completed by pressing the right arrow-key or enter.
This is similar to behaviour in Google Instant Search's query field (Check Example 3 in the demo)
(default: false)
source: (string/array) you can supply an array with items or a string containing a URL to fetch items for the source
this is optional if you prefer to have your own filter method
filter: (function) define a custom function that would return matching items to the entered text (this will override the default filtering algorithm)
should return an array or a Deferred object (ajax call)
parameters available: term, source
resultFormatter: (function) the function you supply here will be called to format the output of an individual result.
should return a string
parameters available: result
resultsContainer: (selector) to which element(s) the result should be appended.
resultElement: (selector) references to the result elements collection (e.g. li, div.result)
Events:
keyIn: fires when user types into the field (parameters: query)
resultsReady: fires when the filter function returns (parameters: results)
showResults: fires when results are shown (parameters: results)
noResults: fires when filter returns an empty array
itemSelect: fires when user selects an item from the result list (paramters: item)
itemFocus: fires when user highlights an item with mouse or arrow keys (paramters: item)
itemUnfocus: fires when user moves out from an highlighted item (paramters: item)
lostFocus: fires when autocomplete field loses focus by user clicking outside of the field or focusing on another field. Also, this event is fired when a value is selected
})
*/
(function($){
$.fn.smartAutoComplete = function(){
if(arguments.length < 1){
// get the smart autocomplete object of the first element and return
var first_element = this[0];
return $(first_element).data("smart-autocomplete")
}
var default_filter_matcher = function(term, source, context){
var matcher = new RegExp(term.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i" );
return $.grep(source, function(value) {
return matcher.test( value );
});
}
var default_options = {
autocompleteTriggered: false,
minCharLimit: 1,
maxCharLimit: null,
maxResults: null,
delay: 0,
disabled: false,
forceSelect: false,
typeAhead: false,
resultElement: "li",
resultFormatter: function(r){ return ("<li>" + r + "</li>"); },
filter: function(term, source){
var context = this;
var options = $(context).data('smart-autocomplete');
//when source is an array
if($.type(source) === "array") {
// directly map
var results = default_filter_matcher(term, source, context);
return results;
}
//when source is a string
else if($.type(source) === "string"){
// treat the string as a URL endpoint
// pass the query as 'term'
return $.Deferred(function(dfd){
$.ajax({
url: source,
data: {"term": term},
dataType: "json"
}).success( function(data){
dfd.resolve( default_filter_matcher(term, data, context) );
});
}).promise();
}
},
alignResultsContainer: false,
clearResults: function(){
//remove type ahead field
var type_ahead_field = $(this.context).prev(".smart_autocomplete_type_ahead_field");
$(this.context).css({ background: type_ahead_field.css("background") });
type_ahead_field.remove();
//clear results div
$(this.resultsContainer).html("");
},
setCurrentSelectionToContext: function(){
if(this.rawResults.length > 0 && this.currentSelection >= 0)
$(this.context).val(this.rawResults[(this.currentSelection)]);
},
setItemSelected: function(val){
this.itemSelected = val;
},
autocompleteFocused: false,
setAutocompleteFocused: function(val){
this.autocompleteFocused = val;
}
};
//define the default events
$.event.special.keyIn = {
setup: function(){ return false; },
_default: function(ev){
var context = ev.target;
var options = $(context).data("smart-autocomplete");
var source = options.activeSource || null;
var filter = options.filter;
var maxChars = (options.maxCharLimit > 0 ? options.maxCharLimit : Number.POSITIVE_INFINITY)
//event specific data
var query = ev.smartAutocompleteData.query;
options.lastQuery = query;
if(options.disabled || (query.length > maxChars)){
$(context).trigger('lostFocus');
return false;
}
//set item selected property
options.setItemSelected(false);
//set autocomplete focused
options.setAutocompleteFocused(true);
//call the filter function with delay
setTimeout(function(){
$.when( filter.apply(options, [query, options.activeSource]) ).done(function( results ){
//do the trimming
var trimmed_results = (options.maxResults > 0 ? results.splice(0, options.maxResults) : results);
$(context).trigger('resultsReady', [trimmed_results]);
});
}, options.delay);
}
};
$.event.special.resultsReady = {
setup: function(){ return false },
_default: function(ev){
var context = ev.target;
var options = $(context).data("smart-autocomplete");
//event specific data
var results = ev.smartAutocompleteData.results;
//exit if smart complete is disabled
if(options.disabled)
return false;
//clear all previous results
$(context).smartAutoComplete().clearResults();
//save the raw results
options.rawResults = results;
//fire the no match event and exit if no matching results
if(results.length < 1){
$(context).trigger('noResults');
return false
}
//call the results formatter function
var formatted_results = $.map(results, function(result){
return options.resultFormatter.apply(options, [result]);
});
var formatted_results_html = formatted_results.join("");
//append the results to the container
if(options.resultsContainer)
$(options.resultsContainer).append(formatted_results_html);
//trigger results ready event
$(context).trigger('showResults', [results]);
}
};
$.event.special.showResults = {
setup: function(){ return false },
_default: function(ev){
var context = ev.target;
var options = $(context).data("smart-autocomplete");
var results_container = $(options.resultsContainer);
//event specific data
var raw_results = ev.smartAutocompleteData.results;
//type ahead
if(options.typeAhead && (raw_results[0].substr(0, $(context).val().length) == $(context).val()) ){
var suggestion = raw_results[0]; //options.typeAheadExtractor($(context).val(), raw_results[0]);
//add new typeAhead field
$(context).before("<input class='smart_autocomplete_type_ahead_field' type='text' autocomplete='off' disabled='disabled' value='" + suggestion + "'/>");
$(context).css({
position: "relative",
zIndex: 2,
background: 'transparent'
});
var typeAheadField = $(context).prev("input");
typeAheadField.css({
position: "absolute",
zIndex: 1,
overflow: 'hidden',
background: $(context).css("background"),
borderColor: 'transparent',
width: $(context).width(),
color: 'silver'
});
//trigger item over for first item
options.currentSelection = 0;
if(results_container)
$(context).trigger('itemFocus', results_container.children()[options.currentSelection]);
}
//show the results container after aligning it with the field
if(results_container){
if(options.alignResultsContainer){
results_container.css({
position: "absolute",
top: function(){ return $(context).offset().top + $(context).height(); },
left: function(){ return $(context).offset().left; },
width: function(){ return $(context).width(); },
zIndex: 1000
})
}
results_container.show();
}
}
};
$.event.special.noResults = {
setup: function(){ return false },
_default: function(ev){
var context = ev.target;
var options = $(context).data("smart-autocomplete");
var result_container = $(options.resultsContainer);
if(result_container){
//clear previous results
options.clearResults();
}
}
};
$.event.special.itemSelect = {
setup: function(){ return false },
_default: function(ev){
var context = ev.target;
var options = $(context).data("smart-autocomplete");
//event specific data
var selected_item = ev.smartAutocompleteData.item;
//get the text from selected item
var selected_value = $(selected_item).text() || $(selected_item).val();
if (selected_value)
{
//insert the text into the autocomplete field
var oldText = $(context).val();
var newBeginning = oldText.substring(0, options.searchStart).concat(selected_value);
var newIndex = newBeginning.length;
var newEnd = oldText.substring(options.searchStart + options.lastQuery.length);
if (newEnd.length > 0 && newEnd[0] != ' ')
newBeginning = newBeginning.concat(' ');
$(context).val(newBeginning.concat(newEnd));
//set item selected property
options.setItemSelected(true);
//set number of current chars in field
options.originalCharCount = $(context).val().length;
}
//trigger lost focus
$(context).trigger('lostFocus');
}
};
$.event.special.itemFocus = {
setup: function(){ return false },
_default: function(ev){
//event specific data
var item = ev.smartAutocompleteData.item;
$(item).addClass("smart_autocomplete_highlight");
}
};
$.event.special.itemUnfocus = {
setup: function(){ return false },
_default: function(ev){
//event specific data
var item = ev.smartAutocompleteData.item;
$(item).removeClass("smart_autocomplete_highlight");
}
}
$.event.special.lostFocus = {
setup: function(){ return false },
_default: function(ev){
var context = ev.target;
var options = $(context).data("smart-autocomplete");
//if force select is selected and no item is selected, clear currently entered text
if(options.forceSelect && !options.itemSelected)
$(options.context).val("");
//unset autocomplete focused
options.setAutocompleteFocused(false);
//clear results
options.clearResults();
//hide the results container
if(options.resultsContainer)
$(options.resultsContainer).hide();
//set current selection to null
options.currentSelection = null;
if (options.triggerCode != -1)
options.autocompleteTriggered = false;
}
};
var passed_options = arguments[0];
return this.each(function(i) {
//set the options
var options = $.extend(default_options, $(this).data("smart-autocomplete"), passed_options);
//set the context
options['context'] = this;
//initialize source data
if (options['source']){
options['activeSource'] = options['source'];
//set the triggerCode if trigger is set, else set autocompleteTriggered
//to true to work without triggers
if (options['trigger'] && options['trigger'].length > 0){
options['triggerCode'] = options['trigger'].charCodeAt(0);
}
else{
options['triggerCode'] = -1;
options['searchStart'] = 0;
options['autocompleteTriggered'] = true;
}
}
else if(options['sources']){
var sources = options['sources'];
var len = sources.length;
for (var i=0; i<len; i++){
if (i in sources){
var source = sources[i];
var triggerKey = source['trigger'];
source['triggerCode'] = triggerKey && triggerKey.length > 0 ? triggerKey.charCodeAt(0) : -1;
}
}
}
//if a result container is not defined
if($.type(options.resultsContainer) === 'undefined' ){
//define the default result container if it is already not defined
var default_container = $("<ul class='smart_autocomplete_container' style='display:none'></ul>");
default_container.appendTo("body");
options.resultsContainer = default_container;
options.alignResultsContainer = true;
}
$(this).data("smart-autocomplete", options);
// bind user events
$(this).keyup(function(ev){
//get the options
var options = $(this).data("smart-autocomplete");
if(options.autocompleteTriggered) {
//up arrow
if(ev.keyCode == '38'){
if(options.resultsContainer){
var current_selection = options.currentSelection || 0;
var result_suggestions = $(options.resultsContainer).children();
if(current_selection >= 0)
$(options.context).trigger('itemUnfocus', result_suggestions[current_selection] );
if(--current_selection <= 0)
current_selection = 0;
options['currentSelection'] = current_selection;
$(options.context).trigger('itemFocus', [ result_suggestions[current_selection] ] );
}
}
//down arrow
else if(ev.keyCode == '40'){
if(options.resultsContainer && options.resultsContainer.is(':visible')){
var current_selection = options.currentSelection;
var result_suggestions = $(options.resultsContainer).children();
if(current_selection != null && current_selection >= 0)
$(options.context).trigger('itemUnfocus', result_suggestions[current_selection] );
if(isNaN(current_selection) || null == current_selection || (++current_selection >= result_suggestions.length) )
current_selection = 0;
options['currentSelection'] = current_selection;
$(options.context).trigger('itemFocus', [ result_suggestions[current_selection] ] );
}
//trigger keyIn event on down key
else {
$(options.context).trigger('keyIn', [$(this).val()]);
}
}
//right arrow, enter key, and spacebar
else if(ev.keyCode == '39' || ev.keyCode == '13' || ev.keyCode == '32'){
var type_ahead_field = $(options.context).prev('.smart_autocomplete_type_ahead_field');
if(options.resultsContainer && $(options.resultsContainer).is(':visible')){
var current_selection = options.currentSelection;
var result_suggestions = $(options.resultsContainer).children();
$(options.context).trigger('itemSelect', [ result_suggestions[current_selection] ] );
}
else if(options.typeAhead && type_ahead_field.is(':visible'))
$(options.context).trigger('itemSelect', [ type_ahead_field ] );
return false;
}
//ESC key
else if (ev.keyCode == '27' && options.resultsContainer && options.resultsContainer.is(':visible')){
var current_selection = options.currentSelection;
var result_suggestions = $(options.resultsContainer).children();
if(current_selection != null && current_selection >= 0)
$(options.context).trigger('itemUnfocus', result_suggestions[current_selection] );
options['currentSelection'] = null;
}
else {
var current_char_count = ev.target.selectionStart - options.searchStart;
//check whether the string has modified
if(current_char_count == 0 || options.originalCharCount == $(options.context).val().length)
return;
//check minimum and maximum number of characters are typed
if(current_char_count >= options.minCharLimit){
var text = $(this).val().substring(options.searchStart, ev.target.selectionStart);
$(options.context).trigger('keyIn', [ text ]);
}
else{
options.currentSelection = null;
$(options.context).trigger('lostFocus');
}
}
}
});
$(this).keypress(function(ev){
//get the options
var options = $(this).data("smart-autocomplete");
if (!options.autocompleteTriggered)
{
//trigger key
if(options.source && ev.which == options.triggerCode){
options.autocompleteTriggered = true;
}
else if (options.sources)
{
var len = options.sources.length;
for (var i=0; i<len; i++){
if (i in options.sources && options.sources[i].source && ev.which == options.sources[i].triggerCode){
options.autocompleteTriggered = true;
options.activeSource = options.sources[i].source;
break;
}
}
}
if (options.autocompleteTriggered)
{
options.searchStart = ev.target.selectionStart + 1;
}
}
});
$(this).keydown(function(ev){
if(options.autocompleteTriggered) {
if(ev.keyCode == '38' || ev.keyCode == '40')
ev.preventDefault();
}
});
$(this).focus(function(){
//if the field is in a form capture the return key event
$(this).closest("form").bind("keydown.block_for_smart_autocomplete", function(ev){
var type_ahead_field = $(options.context).prev('.smart_autocomplete_type_ahead_field');
if(ev.keyCode == '13'){
if(options.resultsContainer && $(options.resultsContainer).is(':visible')){
var current_selection = options.currentSelection;
var result_suggestions = $(options.resultsContainer).children();
$(options.context).trigger('itemSelect', [ result_suggestions[current_selection] ] );
return false;
}
else if(options.typeAhead && type_ahead_field.is(':visible') ){
$(options.context).trigger('itemSelect', [ type_ahead_field ] );
return false;
}
}
});
if(options.forceSelect){
$(this).select();
}
});
//check for loosing focus on smart complete field and results container
//$(this).blur(function(ev){
$(document).bind("focusin click", function(ev){
if(options.autocompleteFocused){
var elemIsParent = $.contains(options.resultsContainer[0], ev.target);
if(ev.target == options.resultsContainer[0] || ev.target == options.context || elemIsParent) return
$(options.context).closest("form").unbind("keydown.block_for_smart_autocomplete");
$(options.context).trigger('lostFocus');
}
});
//bind events to results container
$(options.resultsContainer).delegate(options.resultElement, 'mouseenter.smart_autocomplete', function(){
var old_selection = options.currentSelection || 0;
var result_suggestions = $(options.resultsContainer).children();
options['currentSelection'] = $(this).prevAll().length;
if (old_selection != options.currentSelection) {
$(options.context).trigger('itemUnfocus', result_suggestions[old_selection]);
}
$(options.context).trigger('itemFocus', [this] );
});
$(options.resultsContainer).delegate(options.resultElement, 'mouseleave.smart_autocomplete', function(){
$(options.context).trigger('itemUnfocus', [this] );
});
$(options.resultsContainer).delegate(options.resultElement, 'mousedown.smart_autocomplete', function(){
$(options.context).trigger('itemSelect', [this]);
return false
});
//bind plugin specific events
$(this).bind({
keyIn: function(ev, query){ ev.smartAutocompleteData = {'query': query }; },
resultsReady: function(ev, results){ ev.smartAutocompleteData = {'results': results }; },
showResults: function(ev, results){ ev.smartAutocompleteData = {'results': results } },
noResults: function(){},
lostFocus: function(){},
itemSelect: function(ev, item){ ev.smartAutocompleteData = {'item': item }; },
itemFocus: function(ev, item){ ev.smartAutocompleteData = {'item': item }; },
itemUnfocus: function(ev, item){ ev.smartAutocompleteData = {'item': item }; }
});
});
}
})(jQuery);