-
Notifications
You must be signed in to change notification settings - Fork 0
/
typeahead.js
3938 lines (3452 loc) · 157 KB
/
typeahead.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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* jQuery Typeahead
* Copyright (C) 2020 RunningCoder.org
* Licensed under the MIT license
*
* @author Tom Bertrand
* @version 2.11.1 (2020-5-18)
* @link http://www.runningcoder.org/jquerytypeahead/
*/
console.log("Hello");
(function (factory) {
if (typeof define === "function" && define.amd) {
define("jquery-typeahead", ["jquery"], function (jQuery) {
return factory(jQuery);
});
} else if (typeof module === "object" && module.exports) {
module.exports = (function (jQuery, root) {
if (jQuery === undefined) {
if (typeof window !== "undefined") {
jQuery = require("jquery");
} else {
jQuery = require("jquery")(root);
}
}
return factory(jQuery);
})();
} else {
factory(jQuery);
}
})(function ($) {
"use strict";
window.Typeahead = {
version: '2.11.1'
};
/**
* @private
* Default options
* @link http://www.runningcoder.org/jquerytypeahead/documentation/
*/
var _options = {
input: null, // *RECOMMENDED*, jQuery selector to reach Typeahead's input for initialization
minLength: 2, // Accepts 0 to search on focus, minimum character length to perform a search
maxLength: false, // False as "Infinity" will not put character length restriction for searching results
maxItem: 8, // Accepts 0 / false as "Infinity" meaning all the results will be displayed
dynamic: false, // When true, Typeahead will get a new dataset from the source option on every key press
delay: 300, // delay in ms when dynamic option is set to true
order: null, // "asc" or "desc" to sort results
offset: false, // Set to true to match items starting from their first character
hint: false, // Added support for excessive "space" characters
accent: false, // Will allow to type accent and give letter equivalent results, also can define a custom replacement object
highlight: true, // Added "any" to highlight any word in the template, by default true will only highlight display keys
multiselect: null, // Multiselect configuration object, see documentation for all options
group: false, // Improved feature, Boolean,string,object(key, template (string, function))
groupOrder: null, // New feature, order groups "asc", "desc", Array, Function
maxItemPerGroup: null, // Maximum number of result per Group
dropdownFilter: false, // Take group options string and create a dropdown filter
dynamicFilter: null, // Filter the typeahead results based on dynamic value, Ex: Players based on TeamID
backdrop: false, // Add a backdrop behind Typeahead results
backdropOnFocus: false, // Display the backdrop option as the Typeahead input is :focused
cache: false, // Improved option, true OR 'localStorage' OR 'sessionStorage'
ttl: 3600000, // Cache time to live in ms
compression: false, // Requires LZString library
searchOnFocus: false, // Display search results on input focus
blurOnTab: true, // Blur Typeahead when Tab key is pressed, if false Tab will go though search results
resultContainer: null, // List the results inside any container string or jQuery object
generateOnLoad: null, // Forces the source to be generated on page load even if the input is not focused!
mustSelectItem: false, // The submit function only gets called if an item is selected
href: null, // String or Function to format the url for right-click & open in new tab on link results
display: ["display"], // Allows search in multiple item keys ["display1", "display2"]
template: null, // Display template of each of the result list
templateValue: null, // Set the input value template when an item is clicked
groupTemplate: null, // Set a custom template for the groups
correlativeTemplate: false, // Compile display keys, enables multiple key search from the template string
emptyTemplate: false, // Display an empty template if no result
cancelButton: true, // If text is detected in the input, a cancel button will be available to reset the input (pressing ESC also cancels)
loadingAnimation: true, // Display a loading animation when typeahead is doing request / searching for results
asyncResult: false, // If set to true, the search results will be displayed as they are beging received from the requests / async data function
filter: true, // Set to false or function to bypass Typeahead filtering. WARNING: accent, correlativeTemplate, offset & matcher will not be interpreted
matcher: null, // Add an extra filtering function after the typeahead functions
source: null, // Source of data for Typeahead to filter
callback: {
onInit: null, // When Typeahead is first initialized (happens only once)
onReady: null, // When the Typeahead initial preparation is completed
onShowLayout: null, // Called when the layout is shown
onHideLayout: null, // Called when the layout is hidden
onSearch: null, // When data is being fetched & analyzed to give search results
onResult: null, // When the result container is displayed
onLayoutBuiltBefore: null, // When the result HTML is build, modify it before it get showed
onLayoutBuiltAfter: null, // Modify the dom right after the results gets inserted in the result container
onNavigateBefore: null, // When a key is pressed to navigate the results, before the navigation happens
onNavigateAfter: null, // When a key is pressed to navigate the results
onEnter: null, // When an item in the result list is focused
onLeave: null, // When an item in the result list is blurred
onClickBefore: null, // Possibility to e.preventDefault() to prevent the Typeahead behaviors
onClickAfter: null, // Happens after the default clicked behaviors has been executed
onDropdownFilter: null, // When the dropdownFilter is changed, trigger this callback
onSendRequest: null, // Gets called when the Ajax request(s) are sent
onReceiveRequest: null, // Gets called when the Ajax request(s) are all received
onPopulateSource: null, // Perform operation on the source data before it gets in Typeahead data
onCacheSave: null, // Perform operation on the source data before it gets in Typeahead cache
onSubmit: null, // When Typeahead form is submitted
onCancel: null // Triggered if the typeahead had text inside and is cleared
},
selector: {
container: "typeahead__container",
result: "typeahead__result",
list: "typeahead__list",
group: "typeahead__group",
item: "typeahead__item",
empty: "typeahead__empty",
display: "typeahead__display",
query: "typeahead__query",
filter: "typeahead__filter",
filterButton: "typeahead__filter-button",
dropdown: "typeahead__dropdown",
dropdownItem: "typeahead__dropdown-item",
labelContainer: "typeahead__label-container",
label: "typeahead__label",
button: "typeahead__button",
backdrop: "typeahead__backdrop",
hint: "typeahead__hint",
cancelButton: "typeahead__cancel-button"
},
debug: false // Display debug information (RECOMMENDED for dev environment)
};
/**
* @private
* Event namespace
*/
var _namespace = ".typeahead";
/**
* @private
* Accent equivalents
*/
var _accent = {
from: "ãàáäâẽèéëêìíïîõòóöôùúüûñç",
to: "aaaaaeeeeeiiiiooooouuuunc"
};
/**
* #62 IE9 doesn't trigger "input" event when text gets removed (backspace, ctrl+x, etc)
* @private
*/
var _isIE9 = ~window.navigator.appVersion.indexOf("MSIE 9.");
/**
* #193 Clicking on a suggested option does not select it on IE10/11
* @private
*/
var _isIE10 = ~window.navigator.appVersion.indexOf("MSIE 10");
var _isIE11 = ~window.navigator.userAgent.indexOf("Trident")
? ~window.navigator.userAgent.indexOf("rv:11")
: false;
// SOURCE GROUP RESERVED WORDS: ajax, data, url
// SOURCE ITEMS RESERVED KEYS: group, display, data, matchedKey, compiled, href
/**
* @constructor
* Typeahead Class
*
* @param {object} node jQuery input object
* @param {object} options User defined options
*/
var Typeahead = function (node, options) {
this.rawQuery = node.val() || ""; // Unmodified input query
this.query = node.val() || ""; // Input query
this.selector = node[0].selector; // Typeahead instance selector (to reach from window.Typeahead[SELECTOR])
this.deferred = null; // Promise when "input" event in triggered, this.node.triggerHandler('input').then(() => {})
this.tmpSource = {}; // Temp var to preserve the source order for the searchResult function
this.source = {}; // The generated source kept in memory
this.dynamicGroups = []; // Store the source groups that are defined as dynamic
this.hasDynamicGroups = false; // Boolean if at least one of the groups has a dynamic source
this.generatedGroupCount = 0; // Number of groups generated, if limit reached the search can be done
this.groupBy = "group"; // This option will change according to filtering or custom grouping
this.groups = []; // Array of all the available groups, used to build the groupTemplate
this.searchGroups = []; // Array of groups to generate when Typeahead searches data
this.generateGroups = []; // Array of groups to generate when Typeahead requests data
this.requestGroups = []; // Array of groups to request via Ajax
this.result = []; // Results based on Source-query match (only contains the displayed elements)
this.tmpResult = {}; // Temporary object of results, before they get passed to the buildLayout function
this.groupTemplate = ""; // Result template at the {{group}} level
this.resultHtml = null; // HTML Results (displayed elements)
this.resultCount = 0; // Total results based on Source-query match
this.resultCountPerGroup = {}; // Total results based on Source-query match per group
this.options = options; // Typeahead options (Merged default & user defined)
this.node = node; // jQuery object of the Typeahead <input>
this.namespace =
"." +
this.helper.slugify.call(this, this.selector) +
_namespace; // Every Typeahead instance gets its own namespace for events
this.isContentEditable = typeof this.node.attr('contenteditable') !== "undefined"
&& this.node.attr('contenteditable') !== "false";
this.container = null; // Typeahead container, usually right after <form>
this.resultContainer = null; // Typeahead result container (html)
this.item = null; // Selected item
this.items = null; // Multiselect selected items
this.comparedItems = null; // Multiselect items stored for comparison
this.xhr = {}; // Ajax request(s) stack
this.hintIndex = null; // Numeric value of the hint index in the result list
this.filters = { // Filter list for searching, dropdown and dynamic(s)
dropdown: {}, // Dropdown menu if options.dropdownFilter is set
dynamic: {} // Checkbox / Radio / Select to filter the source data
};
this.dropdownFilter = {
static: [], // Objects that has a value
dynamic: []
};
this.dropdownFilterAll = null; // The last "all" definition
this.isDropdownEvent = false; // If a dropdownFilter is clicked, this will be true to trigger the callback
this.requests = {}; // Store the group:request instead of generating them every time
this.backdrop = {}; // The backdrop object
this.hint = {}; // The hint object
this.label = {}; // The label object
this.hasDragged = false; // Will cancel mouseend events if true
this.focusOnly = false; // Focus the input preventing any operations
this.displayEmptyTemplate; // Display the empty template in the result list
this.__construct();
};
Typeahead.prototype = {
_validateCacheMethod: function (cache) {
var supportedCache = ["localStorage", "sessionStorage"],
supported;
if (cache === true) {
cache = "localStorage";
} else if (typeof cache === "string" && !~supportedCache.indexOf(cache)) {
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "extendOptions()",
message: 'Invalid options.cache, possible options are "localStorage" or "sessionStorage"'
});
_debug.print();
}
// {/debug}
return false;
}
supported = typeof window[cache] !== "undefined";
try {
window[cache].setItem("typeahead", "typeahead");
window[cache].removeItem("typeahead");
} catch (e) {
supported = false;
}
return (supported && cache) || false;
},
extendOptions: function () {
this.options.cache = this._validateCacheMethod(this.options.cache);
if (this.options.compression) {
if (typeof LZString !== "object" || !this.options.cache) {
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "extendOptions()",
message: "Missing LZString Library or options.cache, no compression will occur."
});
_debug.print();
}
// {/debug}
this.options.compression = false;
}
}
if (!this.options.maxLength || isNaN(this.options.maxLength)) {
this.options.maxLength = Infinity;
}
if (
typeof this.options.maxItem !== "undefined" && ~[0, false].indexOf(this.options.maxItem)
) {
this.options.maxItem = Infinity;
}
if (
this.options.maxItemPerGroup && !/^\d+$/.test(this.options.maxItemPerGroup)
) {
this.options.maxItemPerGroup = null;
}
if (this.options.display && !Array.isArray(this.options.display)) {
this.options.display = [this.options.display];
}
if (this.options.multiselect) {
this.items = [];
this.comparedItems = [];
if (typeof this.options.multiselect.matchOn === "string") {
this.options.multiselect.matchOn = [this.options.multiselect.matchOn];
}
}
if (this.options.group) {
if (!Array.isArray(this.options.group)) {
if (typeof this.options.group === "string") {
this.options.group = {
key: this.options.group
};
} else if (typeof this.options.group === "boolean") {
this.options.group = {
key: "group"
};
}
this.options.group.key = this.options.group.key || "group";
} else {
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "extendOptions()",
message: "options.group must be a boolean|string|object as of 2.5.0"
});
_debug.print();
}
// {/debug}
}
}
if (this.options.highlight && !~["any", true].indexOf(this.options.highlight)) {
this.options.highlight = false;
}
if (
this.options.dropdownFilter &&
this.options.dropdownFilter instanceof Object
) {
if (!Array.isArray(this.options.dropdownFilter)) {
this.options.dropdownFilter = [this.options.dropdownFilter];
}
for (var i = 0, ii = this.options.dropdownFilter.length; i < ii; ++i) {
this.dropdownFilter[
this.options.dropdownFilter[i].value ? "static" : "dynamic"
].push(this.options.dropdownFilter[i]);
}
}
if (this.options.dynamicFilter && !Array.isArray(this.options.dynamicFilter)) {
this.options.dynamicFilter = [this.options.dynamicFilter];
}
if (this.options.accent) {
if (typeof this.options.accent === "object") {
if (
this.options.accent.from &&
this.options.accent.to &&
this.options.accent.from.length !== this.options.accent.to.length
) {
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "extendOptions()",
message: 'Invalid "options.accent", from and to must be defined and same length.'
});
_debug.print();
}
// {/debug}
}
} else {
this.options.accent = _accent;
}
}
if (this.options.groupTemplate) {
this.groupTemplate = this.options.groupTemplate;
}
if (this.options.resultContainer) {
if (typeof this.options.resultContainer === "string") {
this.options.resultContainer = $(this.options.resultContainer);
}
if (
!(this.options.resultContainer instanceof $) || !this.options.resultContainer[0]
) {
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "extendOptions()",
message: 'Invalid jQuery selector or jQuery Object for "options.resultContainer".'
});
_debug.print();
}
// {/debug}
} else {
this.resultContainer = this.options.resultContainer;
}
}
if (
this.options.group &&
this.options.group.key
) {
this.groupBy = this.options.group.key;
}
// Compatibility onClick callback
if (this.options.callback && this.options.callback.onClick) {
this.options.callback.onClickBefore = this.options.callback.onClick;
delete this.options.callback.onClick;
}
// Compatibility onNavigate callback
if (this.options.callback && this.options.callback.onNavigate) {
this.options.callback.onNavigateBefore = this.options.callback.onNavigate;
delete this.options.callback.onNavigate;
}
this.options = $.extend(true, {}, _options, this.options);
},
unifySourceFormat: function () {
this.dynamicGroups = [];
// source: ['item1', 'item2', 'item3']
if (Array.isArray(this.options.source)) {
this.options.source = {
group: {
data: this.options.source
}
};
}
// source: "http://www.test.com/url.json"
if (typeof this.options.source === "string") {
this.options.source = {
group: {
ajax: {
url: this.options.source
}
}
};
}
if (this.options.source.ajax) {
this.options.source = {
group: {
ajax: this.options.source.ajax
}
};
}
// source: {data: ['item1', 'item2'], url: "http://www.test.com/url.json"}
if (this.options.source.url || this.options.source.data) {
this.options.source = {
group: this.options.source
};
}
var group, groupSource, tmpAjax;
for (group in this.options.source) {
if (!this.options.source.hasOwnProperty(group)) continue;
groupSource = this.options.source[group];
// source: {group: "http://www.test.com/url.json"}
if (typeof groupSource === "string") {
groupSource = {
ajax: {
url: groupSource
}
};
}
// source: {group: {url: ["http://www.test.com/url.json", "json.path"]}}
tmpAjax = groupSource.url || groupSource.ajax;
if (Array.isArray(tmpAjax)) {
groupSource.ajax =
typeof tmpAjax[0] === "string"
? {
url: tmpAjax[0]
}
: tmpAjax[0];
groupSource.ajax.path = groupSource.ajax.path || tmpAjax[1] || null;
delete groupSource.url;
} else {
// source: {group: {url: {url: "http://www.test.com/url.json", method: "GET"}}}
// source: {group: {url: "http://www.test.com/url.json", dataType: "jsonp"}}
if (typeof groupSource.url === "object") {
groupSource.ajax = groupSource.url;
} else if (typeof groupSource.url === "string") {
groupSource.ajax = {
url: groupSource.url
};
}
delete groupSource.url;
}
if (!groupSource.data && !groupSource.ajax) {
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "unifySourceFormat()",
arguments: JSON.stringify(this.options.source),
message: 'Undefined "options.source.' +
group +
'.[data|ajax]" is Missing - Typeahead dropped'
});
_debug.print();
}
// {/debug}
return false;
}
if (groupSource.display && !Array.isArray(groupSource.display)) {
groupSource.display = [groupSource.display];
}
groupSource.minLength =
typeof groupSource.minLength === "number"
? groupSource.minLength
: this.options.minLength;
groupSource.maxLength =
typeof groupSource.maxLength === "number"
? groupSource.maxLength
: this.options.maxLength;
groupSource.dynamic =
typeof groupSource.dynamic === "boolean" || this.options.dynamic;
if (groupSource.minLength > groupSource.maxLength) {
groupSource.minLength = groupSource.maxLength;
}
this.options.source[group] = groupSource;
if (this.options.source[group].dynamic) {
this.dynamicGroups.push(group);
}
groupSource.cache =
typeof groupSource.cache !== "undefined"
? this._validateCacheMethod(groupSource.cache)
: this.options.cache;
if (groupSource.compression) {
if (typeof LZString !== "object" || !groupSource.cache) {
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "unifySourceFormat()",
message: "Missing LZString Library or group.cache, no compression will occur on group: " +
group
});
_debug.print();
}
// {/debug}
groupSource.compression = false;
}
}
}
this.hasDynamicGroups =
this.options.dynamic || !!this.dynamicGroups.length;
return true;
},
init: function () {
console.log("init");
this.helper.executeCallback.call(this, this.options.callback.onInit, [
this.node
]);
this.container = this.node.closest("." + this.options.selector.container);
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "init()",
//'arguments': JSON.stringify(this.options),
message: "OK - Typeahead activated on " + this.selector
});
_debug.print();
}
// {/debug}
},
delegateEvents: function () {
var scope = this,
events = [
"focus" + this.namespace,
"input" + this.namespace,
"propertychange" + this.namespace, // IE8 Fix
"keydown" + this.namespace,
"keyup" + this.namespace, // IE9 Fix
"search" + this.namespace,
"generate" + this.namespace
];
// #149 - Adding support for Mobiles
$("html")
.on("touchmove", function () {
scope.hasDragged = true;
})
.on("touchstart", function () {
scope.hasDragged = false;
});
this.node
.closest("form")
.on("submit", function (e) {
if (
scope.options.mustSelectItem &&
scope.helper.isEmpty(scope.item)
) {
e.preventDefault();
return;
}
if (!scope.options.backdropOnFocus) {
scope.hideLayout();
}
if (scope.options.callback.onSubmit) {
return scope.helper.executeCallback.call(
scope,
scope.options.callback.onSubmit,
[scope.node, this, scope.item || scope.items, e]
);
}
})
.on("reset", function () {
// #221 - Reset Typeahead on form reset.
// setTimeout to re-queue the `input.typeahead` event at the end
setTimeout(function () {
scope.node.trigger("input" + scope.namespace);
// #243 - minLength: 0 opens the Typeahead results
scope.hideLayout();
});
});
// IE8 fix
var preventNextEvent = false;
// IE10/11 fix
if (this.node.attr("placeholder") && (_isIE10 || _isIE11)) {
var preventInputEvent = true;
this.node.on("focusin focusout", function () {
preventInputEvent = !!(!this.value && this.placeholder);
});
this.node.on("input", function (e) {
if (preventInputEvent) {
e.stopImmediatePropagation();
preventInputEvent = false;
}
});
}
this.node
.off(this.namespace)
.on(events.join(" "), function (e, data) {
switch (e.type) {
case "generate":
scope.generateSource(Object.keys(scope.options.source));
break;
case "focus":
if (scope.focusOnly) {
scope.focusOnly = false;
break;
}
if (scope.options.backdropOnFocus) {
scope.buildBackdropLayout();
scope.showLayout();
}
if (scope.options.searchOnFocus && !scope.item) {
scope.deferred = $.Deferred();
scope.assignQuery();
scope.generateSource();
}
break;
case "keydown":
if (e.keyCode === 8
&& scope.options.multiselect
&& scope.options.multiselect.cancelOnBackspace
&& scope.query === ''
&& scope.items.length
) {
scope.cancelMultiselectItem(scope.items.length - 1, null, e);
} else if (e.keyCode && ~[9, 13, 27, 38, 39, 40].indexOf(e.keyCode)) {
preventNextEvent = true;
scope.navigate(e);
}
break;
case "keyup":
if (
_isIE9 &&
scope.node[0].value.replace(/^\s+/, "").toString().length <
scope.query.length
) {
scope.node.trigger("input" + scope.namespace);
}
break;
case "propertychange":
if (preventNextEvent) {
preventNextEvent = false;
break;
}
case "input":
scope.deferred = $.Deferred();
scope.assignQuery();
// #195 Trigger an onCancel event if the Typeahead is cleared
if (scope.rawQuery === "" && scope.query === "") {
e.originalEvent = data || {};
scope.helper.executeCallback.call(
scope,
scope.options.callback.onCancel,
[scope.node, scope.item, e]
);
scope.item = null;
}
scope.options.cancelButton &&
scope.toggleCancelButtonVisibility();
if (
scope.options.hint &&
scope.hint.container &&
scope.hint.container.val() !== ""
) {
if (scope.hint.container.val().indexOf(scope.rawQuery) !== 0) {
scope.hint.container.val("");
if (scope.isContentEditable) {
scope.hint.container.text("");
}
}
}
if (scope.hasDynamicGroups) {
scope.helper.typeWatch(function () {
scope.generateSource();
}, scope.options.delay);
} else {
scope.generateSource();
}
break;
case "search":
scope.searchResult();
scope.buildLayout();
if (scope.result.length ||
(scope.searchGroups.length &&
scope.displayEmptyTemplate)
) {
scope.showLayout();
} else {
scope.hideLayout();
}
scope.deferred && scope.deferred.resolve();
break;
}
return scope.deferred && scope.deferred.promise();
});
if (this.options.generateOnLoad) {
this.node.trigger("generate" + this.namespace);
}
},
assignQuery: function () {
if (this.isContentEditable) {
this.rawQuery = this.node.text();
} else {
this.rawQuery = this.node.val().toString();
}
this.rawQuery = this.rawQuery.replace(/^\s+/, "");
if (this.rawQuery !== this.query) {
this.query = this.rawQuery;
}
},
filterGenerateSource: function () {
this.searchGroups = [];
this.generateGroups = [];
if (this.focusOnly && !this.options.multiselect) return;
for (var group in this.options.source) {
if (!this.options.source.hasOwnProperty(group)) continue;
if (
this.query.length >= this.options.source[group].minLength &&
this.query.length <= this.options.source[group].maxLength
) {
if (
this.filters.dropdown &&
this.filters.dropdown.key === 'group' &&
this.filters.dropdown.value !== group
) {
continue;
}
this.searchGroups.push(group);
if (!this.options.source[group].dynamic && this.source[group]) {
continue;
}
this.generateGroups.push(group);
}
}
},
generateSource: function (generateGroups) {
this.filterGenerateSource();
this.generatedGroupCount = 0;
if (Array.isArray(generateGroups) && generateGroups.length) {
this.generateGroups = generateGroups;
} else if (!this.generateGroups.length) {
this.node.trigger("search" + this.namespace);
return;
}
this.requestGroups = [];
this.options.loadingAnimation && this.container.addClass("loading");
if (!this.helper.isEmpty(this.xhr)) {
for (var i in this.xhr) {
if (!this.xhr.hasOwnProperty(i)) continue;
this.xhr[i].abort();
}
this.xhr = {};
}
var scope = this,
group,
groupData,
groupSource,
cache,
compression,
dataInStorage,
isValidStorage;
for (var i = 0, ii = this.generateGroups.length; i < ii; ++i) {
group = this.generateGroups[i];
groupSource = this.options.source[group];
cache = groupSource.cache;
compression = groupSource.compression;
if (this.options.asyncResult) {
delete this.source[group];
}
if (cache) {
dataInStorage = window[cache].getItem(
"TYPEAHEAD_" + this.selector + ":" + group
);
if (dataInStorage) {
if (compression) {
dataInStorage = LZString.decompressFromUTF16(dataInStorage);
}
isValidStorage = false;
try {
dataInStorage = JSON.parse(dataInStorage + "");
if (
dataInStorage.data &&
dataInStorage.ttl > new Date().getTime()
) {
this.populateSource(dataInStorage.data, group);
isValidStorage = true;
// {debug}
if (this.options.debug) {
_debug.log({
node: this.selector,
function: "generateSource()",
message: 'Source for group "' + group + '" found in ' + cache
});
_debug.print();
}
// {/debug}
} else {
window[cache].removeItem(
"TYPEAHEAD_" + this.selector + ":" + group
);
}
} catch (error) {
console.log(error);
}
if (isValidStorage) continue;
}
}
if (groupSource.data && !groupSource.ajax) {
// #198 Add support for async data source
if (typeof groupSource.data === "function") {
groupData = groupSource.data.call(this);
if (Array.isArray(groupData)) {
scope.populateSource(groupData, group);
} else if (typeof groupData.promise === "function") {
(function (group) {
$.when(groupData).then(function (deferredData) {
if (deferredData && Array.isArray(deferredData)) {
scope.populateSource(deferredData, group);
}
});
})(group);
}
} else {
this.populateSource($.extend(true, [], groupSource.data), group);
}
continue;
}
if (groupSource.ajax) {
if (!this.requests[group]) {
this.requests[group] = this.generateRequestObject(group);
}
this.requestGroups.push(group);
}
}
if (this.requestGroups.length) {
this.handleRequests();
}
if (this.options.asyncResult && this.searchGroups.length !== this.generateGroups) {
this.node.trigger("search" + this.namespace);
}
return !!this.generateGroups.length;
},
generateRequestObject: function (group) {
var scope = this,
groupSource = this.options.source[group];
var xhrObject = {
request: {
url: groupSource.ajax.url || null,
dataType: "json",
beforeSend: function (jqXHR, options) {
// Important to call .abort() in case of dynamic requests
scope.xhr[group] = jqXHR;
var beforeSend =
scope.requests[group].callback.beforeSend ||
groupSource.ajax.beforeSend;
typeof beforeSend === "function" &&
beforeSend.apply(null, arguments);
}
},
callback: {
beforeSend: null,
done: null,
fail: null,
then: null,
always: null
},
extra: {
path: groupSource.ajax.path || null,
group: group
},
validForGroup: [group]
};
if (typeof groupSource.ajax !== "function") {
if (groupSource.ajax instanceof Object) {
xhrObject = this.extendXhrObject(xhrObject, groupSource.ajax);
}
if (Object.keys(this.options.source).length > 1) {
for (var _group in this.requests) {