-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocomplete_deluxe.js
executable file
·444 lines (372 loc) · 13.8 KB
/
autocomplete_deluxe.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
/**
* @file:
* Converts textfield to a autocomplete deluxe widget.
*/
(function($) {
Drupal.autocomplete_deluxe = Drupal.autocomplete_deluxe || {};
Drupal.behaviors.autocomplete_deluxe = {
attach: function(context) {
var autocomplete_settings = Drupal.settings.autocomplete_deluxe;
$('input.autocomplete-deluxe-form').once( function() {
if (autocomplete_settings[$(this).attr('id')].multiple === true) {
new Drupal.autocomplete_deluxe.MultipleWidget(this, autocomplete_settings[$(this).attr('id')]);
} else {
new Drupal.autocomplete_deluxe.SingleWidget(autocomplete_settings[$(this).attr('id')]);
}
});
}
};
/**
* Autogrow plugin which auto resizes the input of the multiple value.
*
* http://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields
*
*/
$.fn.autoGrowInput = function(o) {
o = $.extend({
maxWidth: 1000,
minWidth: 0,
comfortZone: 70
}, o);
this.filter('input:text').each(function(){
var minWidth = o.minWidth || $(this).width(),
val = '',
input = $(this),
testSubject = $('<tester/>').css({
position: 'absolute',
top: -9999,
left: -9999,
width: 'auto',
fontSize: input.css('fontSize'),
fontFamily: input.css('fontFamily'),
fontWeight: input.css('fontWeight'),
letterSpacing: input.css('letterSpacing'),
whiteSpace: 'nowrap'
}),
check = function() {
if (val === (val = input.val())) {return;}
// Enter new content into testSubject
var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
testSubject.html(escaped);
// Calculate new width + whether to change
var testerWidth = testSubject.width(),
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
currentWidth = input.width(),
isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
|| (newWidth > minWidth && newWidth < o.maxWidth);
// Animate width
if (isValidWidthChange) {
input.width(newWidth);
}
};
testSubject.insertAfter(input);
$(this).bind('keyup keydown blur update', check);
});
return this;
};
Drupal.autocomplete_deluxe.empty = {label: '- ' + Drupal.t('None') + ' -', value: "" };
/**
* EscapeRegex function from jquery autocomplete, is not included in drupal.
*/
Drupal.autocomplete_deluxe.escapeRegex = function(value) {
return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/gi, "\\$&");
};
/**
* Filter function from jquery autocomplete, is not included in drupal.
*/
Drupal.autocomplete_deluxe.filter = function(array, term) {
var matcher = new RegExp(Drupal.autocomplete_deluxe.escapeRegex(term), "i");
return $.grep(array, function(value) {
return matcher.test(value.label || value.value || value);
});
};
Drupal.autocomplete_deluxe.Widget = function() {
};
Drupal.autocomplete_deluxe.Widget.prototype.uri = null;
/**
* Allows widgets to filter terms.
* @param term
* A term that should be accepted or not.
* @return {Boolean}
* True if the term should be accepted.
*/
Drupal.autocomplete_deluxe.Widget.prototype.acceptTerm = function(term) {
return true;
};
Drupal.autocomplete_deluxe.Widget.prototype.init = function(settings) {
if ($.browser && $.browser.msie && $.browser.version === "6.0") {
return;
}
this.id = settings.input_id;
this.jqObject = $('#' + this.id);
this.uri = settings.uri;
this.multiple = settings.multiple;
this.required = settings.required;
this.limit = settings.limit;
this.synonyms = typeof settings.use_synonyms == 'undefined' ? false : settings.use_synonyms;
this.wrapper = '""';
if (typeof settings.delimiter == 'undefined') {
this.delimiter = true;
} else {
this.delimiter = settings.delimiter.charCodeAt(0);
}
this.items = new Array();
var self = this;
var parent = this.jqObject.parent();
var parents_parent = this.jqObject.parent().parent();
parents_parent.append(this.jqObject);
parent.remove();
parent = parents_parent;
var generateValues = function(data, term) {
var result = new Array();
for (var terms in data) {
if (self.acceptTerm(terms)) {
result.push({
label: data[terms],
value: terms
});
}
}
if ($.isEmptyObject(result)) {
console.log(parent);
console.log(data);
console.log(term);
result.push({
label: Drupal.t("No results found."),
value: term,
newTerm: true
});
}
return result;
};
var cache = {}
var lastXhr = null;
this.source = function(request, response) {
var term = request.term;
if (term in cache) {
response(generateValues(cache[term], term));
return;
}
// Some server collapse two slashes if the term is empty, so insert at
// least a whitespace. This whitespace will later on be trimmed in the
// autocomplete callback.
if (!term) {
term = " ";
}
request.synonyms = self.synonyms;
var url = settings.uri + '/' + term +'/' + self.limit;
lastXhr = $.getJSON(url, request, function(data, status, xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(generateValues(data, term));
}
});
};
this.jqObject.autocomplete({
'source' : this.source,
'minLength': settings.min_length
});
var jqObject = this.jqObject;
var throbber = $('<span class="input-group-addon form-autocomplete"><i class="icon glyphicon glyphicon-refresh" aria-hidden="true"></i></span>').insertAfter(jqObject);
var icon = throbber.find(":first");
this.jqObject.bind("autocompletesearch", function(event, ui) {
icon.addClass('glyphicon-spin');
});
this.jqObject.bind("autocompleteopen", function(event, ui) {
icon.removeClass('glyphicon-spin');
});
// Monkey patch the _renderItem function jquery so we can highlight the
// text, that we already entered.
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
var t = item.label;
if (this.term != "") {
var escapedValue = Drupal.autocomplete_deluxe.escapeRegex( this.term );
var re = new RegExp('()*""' + escapedValue + '""|' + escapedValue + '()*', 'gi');
var t = item.label.replace(re,"<span class='autocomplete-deluxe-highlight-char'>$&</span>");
}
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
};
Drupal.autocomplete_deluxe.Widget.prototype.generateValues = function(data) {
var result = new Array();
for (var index in data) {
result.push(data[index]);
}
return result;
};
/**
* Generates a single selecting widget.
*/
Drupal.autocomplete_deluxe.SingleWidget = function(settings) {
this.init(settings);
this.setup();
this.jqObject.addClass('autocomplete-deluxe-form-single');
};
Drupal.autocomplete_deluxe.SingleWidget.prototype = new Drupal.autocomplete_deluxe.Widget();
Drupal.autocomplete_deluxe.SingleWidget.prototype.setup = function() {
var jqObject = this.jqObject;
var parent = jqObject.parent();
parent.mousedown(function() {
if (parent.hasClass('autocomplete-deluxe-single-open')) {
jqObject.autocomplete('close');
} else {
jqObject.autocomplete('search', '');
}
});
};
/**
* Creates a multiple selecting widget.
*/
Drupal.autocomplete_deluxe.MultipleWidget = function(input, settings) {
this.init(settings);
this.setup(settings);
};
Drupal.autocomplete_deluxe.MultipleWidget.prototype = new Drupal.autocomplete_deluxe.Widget();
Drupal.autocomplete_deluxe.MultipleWidget.prototype.items = new Array();
Drupal.autocomplete_deluxe.MultipleWidget.prototype.acceptTerm = function(term) {
// Accept only terms, that are not in our items list.
return "true";
// return !(term in this.items);
};
Drupal.autocomplete_deluxe.MultipleWidget.Item = function (widget, item) {
if (item.newTerm === true) {
item.label = item.value;
}
this.value = item.value;
this.element = $('<span class="autocomplete-deluxe-item">' + item.label + '</span>');
this.widget = widget;
this.item = item;
var self = this;
var close = $('<a class="autocomplete-deluxe-item-delete" href="javascript:void(0)"></a>').appendTo(this.element);
// Use single quotes because of the double quote encoded stuff.
var input = $('<input type="hidden" value=\'' + this.value + '\'/>').appendTo(this.element);
close.mousedown(function() {
self.remove(item);
});
};
Drupal.autocomplete_deluxe.MultipleWidget.Item.prototype.remove = function() {
this.element.remove();
var values = this.widget.valueForm.val();
var escapedValue = Drupal.autocomplete_deluxe.escapeRegex( this.item.value );
var regex = new RegExp('()*""' + escapedValue + '""|' + escapedValue + '()*', 'gi');
this.widget.valueForm.val(values.replace(regex, ''));
var findIndex = this.wiget.items.indexOf(this.value);
delete this.widget.items[findIndex];
};
Drupal.autocomplete_deluxe.MultipleWidget.prototype.setup = function(settings) {
var jqObject = this.jqObject;
var parent = jqObject.parents('.autocomplete-deluxe-container');
var value_container = parent.next();
var value_input = value_container.find('input');
var items = this.items;
var self = this;
this.valueForm = value_input;
jqObject.show();
value_container.hide();
// Add the default values to the box.
var default_values = value_input.val();
default_values = $.trim(default_values);
default_values = default_values.substr(2, default_values.length-4);
default_values = default_values.split('"" ""');
for (var index in default_values) {
var value = default_values[index];
if (value != '') {
// If a terms is encoded in double quotes, then the label should have
// no double quotes.
var label = value.match(/["][\w|\s|\D|]*["]/gi) !== null ? value.substr(1, value.length-2) : value;
var item = {
label : label,
value : value
};
var item = new Drupal.autocomplete_deluxe.MultipleWidget.Item(self, item);
item.element.insertBefore(jqObject);
items.push(item);
}
}
jqObject.addClass('autocomplete-deluxe-multiple');
parent.addClass('autocomplete-deluxe-multiple');
// Adds a value to the list.
this.addValue = function(ui_item) {
var item = new Drupal.autocomplete_deluxe.MultipleWidget.Item(self, ui_item);
item.element.insertBefore(jqObject);
items.push(item);
var new_value = ' ' + self.wrapper + ui_item.value + self.wrapper;
var values = value_input.val();
value_input.val(values + new_value);
jqObject.val('');
};
parent.mouseup(function() {
jqObject.autocomplete('search', '');
jqObject.focus();
});
jqObject.bind("autocompleteselect", function(event, ui) {
self.addValue(ui.item);
jqObject.width(25);
// Return false to prevent setting the last term as value for the jqObject.
return false;
});
jqObject.bind("autocompletechange", function(event, ui) {
jqObject.val('');
});
jqObject.blur(function() {
var last_element = jqObject.parent().children('.autocomplete-deluxe-item').last();
last_element.removeClass('autocomplete-deluxe-item-focus');
});
var clear = false;
jqObject.keypress(function (event) {
var value = jqObject.val();
// If a comma was entered and there is none or more then one comma,or the
// enter key was entered, then enter the new term.
if ((event.which == self.delimiter && (value.split('"').length - 1) != 1) || (event.which == 13 && jqObject.val() != "")) {
value = value.substr(0, value.length);
var valueIndex = self.items.indexOf(value);
if (typeof self.items[valueIndex] == 'undefined' && value != '') {
var ui_item = {
label: value,
value: value
};
self.addValue(ui_item);
}
clear = true;
if (event.which == 13) {
return false;
}
}
// If the Backspace key was hit and the input is empty
if (event.which == 8 && value == '') {
var last_element = jqObject.parent().children('.autocomplete-deluxe-item').last();
// then mark the last item for deletion or deleted it if already marked.
if (last_element.hasClass('autocomplete-deluxe-item-focus')) {
var value = last_element.children('input').val();
var valueIndex = self.items.indexOf(value);
self.items[valueIndex].remove(self.items[valueIndex]);
jqObject.autocomplete('search', '');
} else {
last_element.addClass('autocomplete-deluxe-item-focus');
}
} else {
// Remove the focus class if any other key was hit.
var last_element = jqObject.parent().children('.autocomplete-deluxe-item').last();
last_element.removeClass('autocomplete-deluxe-item-focus');
}
});
jqObject.autoGrowInput({
comfortZone: 50,
minWidth: 10,
maxWidth: 460
});
jqObject.keyup(function (event) {
if (clear) {
// Trigger the search, so it display the values for an empty string.
jqObject.autocomplete('search', '');
jqObject.val('');
clear = false;
// Return false to prevent entering the last character.
return false;
}
});
};
})(jQuery);