forked from issa-tseng/awesomecomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.awesomecomplete.js
executable file
·332 lines (296 loc) · 11.8 KB
/
jquery.awesomecomplete.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
/**
* Awesomecomplete — A lightweight, simple autocomplete plugin
* Clint Tseng ([email protected]) — 2009-08-20
* I think licenses are dumb and superfluous. I'm releasing this into the
* wild under public domain, but please do let me know what you think!
*/
(function($)
{
var ident = 0;
// Initializer. Call on a text field to make things go.
$.fn.awesomecomplete = function(options)
{
var options = $.extend({}, $.fn.awesomecomplete.defaults, options);
return this.each(function()
{
var $this = $(this);
var config = $.meta ? $.extend({}, options, $this.data()) : options;
$this.data('awesomecomplete-config', config);
var $attachTo = $(config.attachTo || $this);
var $list = $('<ul/>').addClass(config.suggestionListClass)
.insertAfter($attachTo)
.hide()
.css('width', $attachTo.innerWidth());
$this.data('awesomecomplete-list', $list);
var typingDelayPointer;
var suppressKey = false;
$this.keyup(function(event)
{
if (suppressKey)
{
suppressKey = false;
return;
}
// ignore arrow keys, shift
if ( ((event.which > 36) && (event.which < 41)) ||
(event.which == 16) )
return;
if (config.typingDelay > 0)
{
clearTimeout(typingDelayPointer);
typingDelayPointer = setTimeout(function() { processInput($this); }, config.typingDelay);
}
else
{
processInput($this);
}
});
$this.keydown(function(event)
{
// enter = 13; up = 38; down = 40; esc = 27
var $active = $list.children('li.' + config.activeItemClass);
switch (event.which)
{
case 13:
if (($active.length !== 0) && ($list.is(':visible')))
{
event.preventDefault();
$this.val($active.data('awesomecomplete-value'));
config.onComplete($active.data('awesomecomplete-dataItem'));
$list.hide();
}
$list.hide();
suppressKey = true;
break;
case 38:
event.preventDefault();
if ($active.length === 0)
{
$list.children('li:last-child').addClass(config.activeItemClass);
}
else
{
$active.prev().addClass(config.activeItemClass);
$active.removeClass(config.activeItemClass);
}
break;
case 40:
event.preventDefault();
if ($active.length === 0)
{
$list.children('li:first-child').addClass(config.activeItemClass);
}
else if ($active.is(':not(:last-child)'))
{
$active.next().addClass(config.activeItemClass);
$active.removeClass(config.activeItemClass);
}
break;
case 27:
$list.hide();
suppressKey = true;
break;
}
});
// opera wants keypress rather than keydown to prevent the form submit
$this.keypress(function(event)
{
var $active = $list.children('li.' + config.activeItemClass);
if ((event.which == 13) && ($list.children('li.' + config.activeItemClass).length > 0))
{
event.preventDefault();
}
});
// stupid hack to get around loss of focus on mousedown
var mouseDown = false;
var blurWait = false;
$(document).bind('mousedown.awesomecomplete' + ++ident, function()
{
mouseDown = true;
});
$(document).bind('mouseup.awesomecomplete' + ident, function()
{
mouseDown = false;
if (blurWait)
{
blurWait = false;
$list.hide();
}
});
$this.blur(function()
{
if (mouseDown)
{
blurWait = true;
}
else
{
var $active = $list.children('li.' + config.activeItemClass);
if ($list.is(':visible') && ($active.length !== 0))
$this.val($active.data('awesomecomplete-value'));
$list.hide();
}
});
$this.focus(function()
{
if ($list.children(':not(.' + config.noResultsClass + ')').length > 0)
$list.show();
});
});
};
// Data callback. If you're using callbacks to a server,
// call this on the autocompleted text field to complete the
// callback process after you have your matching items.
var onDataProxy = function($this, term)
{
return function(data)
{
processData($this, data, term);
};
}
// private helpers
var processInput = function($this)
{
var term = $this.val();
if (typeof $this.data('awesomecomplete-config').dataMethod === 'function')
$this.data('awesomecomplete-config').dataMethod(term, $this, onDataProxy($this, term));
else
processData($this, $this.data('awesomecomplete-config').staticData, term);
};
var processData = function($this, data, term)
{
var $list = $this.data('awesomecomplete-list');
$list.empty().hide();
if (term === '')
return;
var config = $this.data('awesomecomplete-config');
var results = [];
for (var item = 0; item < data.length; item++)
{
var dataItem = jQuery.extend({}, data[item]);
var matchCount = 0;
var maxFieldMatches = 0;
var topMatch = null;
var matchedTerms = [];
for (var field in dataItem)
{
if ((typeof dataItem[field] === 'function') || (typeof dataItem[field] === 'object'))
continue;
var skippedField = false;
for (var j = 0; j < config.dontMatch.length; j++)
if (field == config.dontMatch[j])
skippedField = true;
if (skippedField)
continue;
var dataString = dataItem[field].toString();
var terms = [ term ];
if (config.splitTerm)
terms = term.split(config.wordDelimiter);
for (var j = 0; j < terms.length; j++)
{
if (terms[j] === '')
continue;
terms[j] = terms[j].replace(/[\\*+?|{}()^$.#]/g, '\\$1');
var regex = new RegExp('(' + terms[j] + ')', (config.ignoreCase ? 'ig' : 'g'));
var matches = [];
if (matches = dataString.match(regex))
{
matchCount += matches.length;
if ((field != config.nameField) && (matches.length > maxFieldMatches))
{
maxFieldMatches = matches.length;
topMatch = field;
matchedTerms[j] = true;
}
}
}
if (config.highlightMatches)
{
var regex = new RegExp('(' + terms.join('|') + ')', (config.ignoreCase ? 'ig' : 'g'));
dataItem[field] = dataString.replace(regex, '<span class="' + config.highlightClass + '">$1</span>');
}
}
var matchedTermCount = 0;
for (var j = 0; j < matchedTerms.length; j++)
if (matchedTerms[j] === true)
matchedTermCount++;
if (matchCount > 0)
results.push({
dataItem: dataItem,
originalDataItem: data[item],
matchCount: matchCount,
topMatch: topMatch,
matchedTermCount: matchedTermCount
});
}
results.sort(function(a, b)
{
return config.sortFunction(a, b, term);
});
results = results.slice(0, config.resultLimit);
for (var i in results)
{
$('<li>' + config.renderFunction(results[i].dataItem, results[i].topMatch, results[i].originalDataItem, config) + '</li>')
.data('awesomecomplete-dataItem', results[i].originalDataItem)
.data('awesomecomplete-value', config.valueFunction(results[i].originalDataItem, config))
.appendTo($list)
.click(function()
{
var $listItem = $(this);
$this.val($listItem.data('awesomecomplete-value'));
config.onComplete($listItem.data('awesomecomplete-dataItem'));
})
.mouseover(function()
{
$(this).addClass(config.activeItemClass)
.siblings().removeClass(config.activeItemClass);
});
}
if ((config.noResultsMessage !== undefined) && (results.length == 0))
$list.append($('<li class="' + config.noResultsClass + '">' + config.noResultsMessage + '</li>'));
if ((results.length > 0) || (config.noResultsMessage !== undefined))
$list.show();
};
// default functions
var defaultRenderFunction = function(dataItem, topMatch, originalDataItem, config)
{
if ((topMatch === config.nameField) || (topMatch === null))
return '<p class="title">' + dataItem[config.nameField] + '</p>';
else
return '<p class="title">' + dataItem[config.nameField] + '</p>' +
'<p class="matchRow"><span class="matchedField">' + topMatch + '</span>: ' +
dataItem[topMatch] + '</p>';
};
var defaultValueFunction = function(dataItem, config)
{
return dataItem[config.nameField];
};
var defaultSortFunction = function(a, b, term)
{
return (a.matchedTermCount == b.matchedTermCount) ?
(b.matchCount - a.matchCount) :
(b.matchedTermCount - a.matchedTermCount);
};
$.fn.awesomecomplete.defaults = {
activeItemClass: 'active',
attachTo: undefined,
dataMethod: undefined,
dontMatch: [],
highlightMatches: true,
highlightClass: 'match',
ignoreCase: true,
nameField: 'name',
noResultsClass: 'noResults',
noResultsMessage: undefined,
onComplete: function(dataItem) {},
sortFunction: defaultSortFunction,
splitTerm: true,
staticData: [],
suggestionListClass: "autocomplete",
renderFunction: defaultRenderFunction,
resultLimit: 10,
typingDelay: 0,
valueFunction: defaultValueFunction,
wordDelimiter: /[^\da-z]+/ig
};
})(jQuery);