-
Notifications
You must be signed in to change notification settings - Fork 2k
/
autocomplete.js
273 lines (243 loc) · 8.54 KB
/
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
/* An auto-complete module for select and input elements that can pull in
* a list of terms from an API endpoint (provided using data-module-source).
*
* source - A url pointing to an API autocomplete endpoint.
* interval - The interval between requests in milliseconds (default: 1000).
* items - The max number of items to display (default: 10)
* tags - Boolean attribute if true will create a tag input.
* key - A string of the key you want to be the form value to end up on
* from the ajax returned results
* label - A string of the label you want to appear within the dropdown for
* returned results
*
* Examples
*
* // <input name="tags" data-module="autocomplete" data-module-source="http://" />
*
*/
this.ckan.module('autocomplete', function (jQuery, _) {
return {
/* Options for the module */
options: {
tags: false,
key: false,
label: false,
items: 10,
source: null,
interval: 1000,
dropdownClass: '',
containerClass: '',
i18n: {
noMatches: _('No matches found'),
emptySearch: _('Start typing…'),
inputTooShort: function (data) {
return _('Input is too short, must be at least one character')
.ifPlural(data.min, 'Input is too short, must be at least %(min)d characters');
}
}
},
/* Sets up the module, binding methods, creating elements etc. Called
* internally by ckan.module.initialize();
*
* Returns nothing.
*/
initialize: function () {
jQuery.proxyAll(this, /_on/, /format/);
this.setupAutoComplete();
},
/* Sets up the auto complete plugin.
*
* Returns nothing.
*/
setupAutoComplete: function () {
var settings = {
width: 'resolve',
formatResult: this.formatResult,
formatNoMatches: this.formatNoMatches,
formatInputTooShort: this.formatInputTooShort,
dropdownCssClass: this.options.dropdownClass,
containerCssClass: this.options.containerClass
};
// Different keys are required depending on whether the select is
// tags or generic completion.
if (!this.el.is('select')) {
if (this.options.tags) {
settings.tags = this._onQuery;
} else {
settings.query = this._onQuery;
settings.createSearchChoice = this.formatTerm;
}
settings.initSelection = this.formatInitialValue;
}
var select2 = this.el.select2(settings).data('select2');
if (this.options.tags && select2 && select2.search) {
// find the "fake" input created by select2 and add the keypress event.
// This is not part of the plugins API and so may break at any time.
select2.search.on('keydown', this._onKeydown);
}
// This prevents Internet Explorer from causing a window.onbeforeunload
// even from firing unnecessarily
$('.select2-choice', select2.container).on('click', function() {
return false;
});
this._select2 = select2;
},
/* Looks up the completions for the current search term and passes them
* into the provided callback function.
*
* The results are formatted for use in the select2 autocomplete plugin.
*
* string - The term to search for.
* fn - A callback function.
*
* Examples
*
* module.getCompletions('cake', function (results) {
* results === {results: []}
* });
*
* Returns a jqXHR promise.
*/
getCompletions: function (string, fn) {
var parts = this.options.source.split('?');
var end = parts.pop();
var source = parts.join('?') + encodeURIComponent(string) + end;
var client = this.sandbox.client;
var options = {
format: function(data) {
var completion_options = jQuery.extend(options, {objects: true});
return {
results: client.parseCompletions(data, completion_options)
}
},
key: this.options.key,
label: this.options.label
};
return client.getCompletions(source, options, fn);
},
/* Looks up the completions for the provided text but also provides a few
* optimisations. If there is no search term it will automatically set
* an empty array. Ajax requests will also be debounced to ensure that
* the server is not overloaded.
*
* string - The term to search for.
* fn - A callback function.
*
* Returns nothing.
*/
lookup: function (string, fn) {
var module = this;
// Cache the last searched term otherwise we'll end up searching for
// old data.
this._lastTerm = string;
// Kills previous timeout
clearTimeout(this._debounced);
// OK, wipe the dropdown before we start ajaxing the completions
fn({results:[]});
if (string) {
// Set a timer to prevent the search lookup occurring too often.
this._debounced = setTimeout(function () {
var term = module._lastTerm;
// Cancel the previous request if it hasn't yet completed.
if (module._last && typeof module._last.abort == 'function') {
module._last.abort();
}
module._last = module.getCompletions(term, fn);
}, this.options.interval);
// This forces the ajax throbber to appear, because we've called the
// callback already and that hides the throbber
$('.select2-search input', this._select2.dropdown).addClass('select2-active');
}
},
/* Formatter for the select2 plugin that returns a string for use in the
* results list with the current term emboldened.
*
* state - The current object that is being rendered.
* container - The element the content will be added to (added in 3.0)
* query - The query object (added in select2 3.0).
*
*
* Returns a text string.
*/
formatResult: function (state, container, query) {
var term = this._lastTerm || null; // same as query.term
if (container) {
// Append the select id to the element for styling.
container.attr('data-value', state.id);
}
return state.text.split(term).join(term && term.bold());
},
/* Formatter for the select2 plugin that returns a string used when
* the filter has no matches.
*
* Returns a text string.
*/
formatNoMatches: function (term) {
return !term ? this.i18n('emptySearch') : this.i18n('noMatches');
},
/* Formatter used by the select2 plugin that returns a string when the
* input is too short.
*
* Returns a string.
*/
formatInputTooShort: function (term, min) {
return this.i18n('inputTooShort', {min: min});
},
/* Takes a string and converts it into an object used by the select2 plugin.
*
* term - The term to convert.
*
* Returns an object for use in select2.
*/
formatTerm: function (term) {
term = jQuery.trim(term || '');
// Need to replace comma with a unicode character to trick the plugin
// as it won't split this into multiple items.
return {id: term.replace(/,/g, '\u002C'), text: term};
},
/* Callback function that parses the initial field value.
*
* element - The initialized input element wrapped in jQuery.
* callback - A callback to run once the formatting is complete.
*
* Returns a term object or an array depending on the type.
*/
formatInitialValue: function (element, callback) {
var value = jQuery.trim(element.val() || '');
var formatted;
if (this.options.tags) {
formatted = jQuery.map(value.split(","), this.formatTerm);
} else {
formatted = this.formatTerm(value);
}
// Select2 v3.0 supports a callback for async calls.
if (typeof callback === 'function') {
callback(formatted);
}
return formatted;
},
/* Callback triggered when the select2 plugin needs to make a request.
*
* Returns nothing.
*/
_onQuery: function (options) {
if (options) {
this.lookup(options.term, options.callback);
}
},
/* Called when a key is pressed. If the key is a comma we block it and
* then simulate pressing return.
*
* Returns nothing.
*/
_onKeydown: function (event) {
if (event.which === 188) {
event.preventDefault();
setTimeout(function () {
var e = jQuery.Event("keydown", { which: 13 });
jQuery(event.target).trigger(e);
}, 10);
}
}
};
});