-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
382 lines (316 loc) · 7.3 KB
/
index.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
/**
* Module dependencies
*/
var throttle = require('throttle'),
classes = require('classes'),
event = require('event'),
toFunction = require('to-function'),
map = require('map'),
Menu = require('menu'),
Emitter = require('emitter'),
request = require('superagent'),
noop = function() {};
/**
* Export `Autocomplete`
*/
module.exports = Autocomplete;
/**
* Initialize `Autocomplete`
*/
function Autocomplete(el, url, opts) {
if(!(this instanceof Autocomplete)) return new Autocomplete(el, url, opts);
opts = opts || {};
this.el = el;
this.coords = getOffset(el);
this.url = url;
this._when = false;
this._display = true;
this.throttle = opts.throttle || 200;
this.headers = opts.headers || {};
this.throttledSearch = throttle(this.search.bind(this), this.throttle);
this._key = el.getAttribute('name');
this.formatter = function(item) { return item; };
// Prevents the native autocomplete from showing up
this.el.setAttribute('autocomplete', 'off');
classes(this.el).add('autocomplete');
Emitter.call(this);
this.enable();
}
/**
* Mixin `Emitter`
*/
Emitter(Autocomplete.prototype);
/**
* Enable the autocomplete
*
* @return {Autocomplete}
*/
Autocomplete.prototype.enable = function() {
this.emit('enabled');
event.bind(this.el, 'keyup', this.throttledSearch);
return this;
};
/**
* Disable the autocomplete
*
* @return {Autocomplete}
*/
Autocomplete.prototype.disable = function() {
this.emit('disabled');
event.unbind(this.el, 'keyup', this.throttledSearch);
return this;
};
/**
* #display(boolean)
*
* Display the menu or not. Defaults to `true`
*
* @param {Boolean} display
* @return {Autocomplete}
*/
Autocomplete.prototype.display = function(display) {
this._display = display;
return this;
};
/**
* Set the key for the search endpoint
*
* @param {String} key
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.key = function(key) {
this._key = key;
return this;
};
/**
* #parse(fn)
*
* Handles parsing the response
*
* @param {Function} fn
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.parse = function(fn) {
this._parse = fn;
return this;
};
/**
* #label(str|func)
*
* Determines which label to show in the menu
*
* @param {String|Function} label
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.label =
Autocomplete.prototype.labels = function(label) {
this._label = label;
return this;
};
/**
* #value(str|func)
*
* Determines which value we use when we select an item
*
* @param {String|Function} value
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.value =
Autocomplete.prototype.values = function(value) {
this._value = value;
return this;
};
/**
* #format(format)
*
* Applies formatting to the label that's displayed
*
* @param {Function} format
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.format = function(format) {
this.formatter = format;
return this;
};
/**
* #when(regex|fn)
*
* Only autocomplete when the input meets
* the passes the `filter`
*
* @param {Regexp|Function} filter
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.when = function(filter) {
this._when = 'function' != typeof filter
? function (v) { return filter.test(v); }
: filter;
return this;
};
/**
* #search([fn])
*
* Search with the given input. An optional callback
* is provided with results
*
* @param {Function} fn
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.search = function(fn) {
if(fn && (fn.keyCode == 13 || fn.keyCode == 27)) return this;
else if(typeof fn !== 'function') fn = noop;
// filter out invalid results
if (this._when && !this._when(this.el.value)) return this;
if(!this._key)
throw new Error('autocomplete: no key to query on, add key in input[name] or key()');
var self = this,
url = this.url,
headers = this.headers,
val = encodeURIComponent(this.el.value),
rkey = new RegExp(':' + this._key);
query = {};
if(!val) {
if(this.menu) this.menu.hide();
return this;
}
// Add basic search/:keyword
if(rkey.test(url)) {
url = url.replace(rkey, val);
} else {
query[this._key] = val;
}
request
.get(url)
.set(headers)
.query(query)
.end(this.respond.bind(this, fn, this.el.value));
return this;
};
/**
* #select(value)
*
* Handle the selecting of a menu item
*
* @param {Mixed} value
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.select = function(value) {
this.emit('select', value);
return this;
};
/**
* Customize the position of the `Menu`
*
* @param {Function} fn
* @return {Autocomplete}
* @api public
*/
Autocomplete.prototype.position = function(fn) {
this._position = fn;
return this;
};
/**
* Default positioning of the `Menu`. May be overwritten
* to provide custom positioning logic
*
* @param {Node} el
* @return {Object}
* @api private
*/
Autocomplete.prototype._position = function(el) {
var coords = getOffset(el),
x = coords.left,
y = coords.top + el.offsetHeight;
return { x : x, y : y };
};
/**
* #respond(res)
*
* Handles the superagent response
*
* @param {Function} fn
* @param {String} query
* @param {Object} res
* @return {Autocomplete}
* @api private
*/
Autocomplete.prototype.respond = function(fn, query, res) {
if(!res.ok) {
this.emit('error', res.text);
fn(res.text);
return this;
}
var parser = toFunction(this._parse || function(obj) { return obj; }),
items = parser(res.body);
if(!isArray(items)) throw new Error('autocomplete: response is not an array');
this.emit('response', items);
fn(null, items);
if(!this._display) {
return this;
} else if(!this._label || !this._value) {
throw new Error('autocomplete: dont know how to render menu need to specify #label(k) and #value(k)');
}
var el = this.el,
labels = map(items, this._label),
values = map(items, this._value),
len = labels.length,
menu = this.menu = this.menu || new Menu,
format = this.formatter,
pos = this._position(this.el);
// Add `autocomplete` class to menu
classes(menu.el).add('autocomplete');
// Reset the menu
this.menu.hide().clear().off('select');
labels.forEach(function(label, i) {
var value = values[i];
menu.add(value, format(label, query));
menu.on(value, function() {
el.value = label;
el.focus();
});
});
// Pass select event onto autocomplete
menu.on('select', this.select.bind(this));
// Position the menu
menu.moveTo(pos.x, pos.y);
// If we have items to show, show it.
if(items.length) menu.show();
return this;
};
/**
* Cross-browser Array#isArray
*
* @param {Array} arr
* @return {Boolean}
* @api private
*/
function isArray (arr) {
return (Array.isArray)
? Array.isArray(arr)
: Object.prototype.toString.call(arr) === "[object Array]";
}
/**
* Cross-browser way to get element offset
*
* @param {Node} el
* @return {Object}
* @api private
*/
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}