forked from denis-taran/autocomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete.js
395 lines (392 loc) · 14.4 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
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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.autocomplete = factory());
}(this, (function () { 'use strict';
/*
* https://github.com/kraaden/autocomplete
* Copyright (c) 2016 Denys Krasnoshchok
* MIT License
*/
function autocomplete(settings) {
// just an alias to minimize JS file size
var doc = document;
var container = doc.createElement("div");
var containerStyle = container.style;
var userAgent = navigator.userAgent;
var mobileFirefox = userAgent.indexOf("Firefox") !== -1 && userAgent.indexOf("Mobile") !== -1;
var debounceWaitMs = settings.debounceWaitMs || 0;
var preventSubmit = settings.preventSubmit || false;
var allowSubmitOnTab = settings.allowSubmitOnTab || false;
// 'keyup' event will not be fired on Mobile Firefox, so we have to use 'input' event instead
var keyUpEventName = mobileFirefox ? "input" : "keyup";
var items = [];
var inputValue = "";
var minLen = 2;
var showOnFocus = settings.showOnFocus;
var selected;
var keypressCounter = 0;
var debounceTimer;
if (settings.minLength !== undefined) {
minLen = settings.minLength;
}
if (!settings.input) {
throw new Error("input undefined");
}
var input = settings.input;
container.className = "autocomplete " + (settings.className || "");
// IOS implementation for fixed positioning has many bugs, so we will use absolute positioning
containerStyle.position = "absolute";
/**
* Detach the container from DOM
*/
function detach() {
var parent = container.parentNode;
if (parent) {
parent.removeChild(container);
}
}
/**
* Clear debouncing timer if assigned
*/
function clearDebounceTimer() {
if (debounceTimer) {
window.clearTimeout(debounceTimer);
}
}
/**
* Attach the container to DOM
*/
function attach() {
if (!container.parentNode) {
doc.body.appendChild(container);
}
}
/**
* Check if container for autocomplete is displayed
*/
function containerDisplayed() {
return !!container.parentNode;
}
/**
* Clear autocomplete state and hide container
*/
function clear() {
// prevent the update call if there are pending AJAX requests
keypressCounter++;
items = [];
inputValue = "";
selected = undefined;
detach();
}
/**
* Update autocomplete position
*/
function updatePosition() {
if (!containerDisplayed()) {
return;
}
containerStyle.height = "auto";
containerStyle.width = input.offsetWidth + "px";
var maxHeight = 0;
var inputRect;
function calc() {
var docEl = doc.documentElement;
var clientTop = docEl.clientTop || doc.body.clientTop || 0;
var clientLeft = docEl.clientLeft || doc.body.clientLeft || 0;
var scrollTop = window.pageYOffset || docEl.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft;
inputRect = input.getBoundingClientRect();
var top = inputRect.top + input.offsetHeight + scrollTop - clientTop;
var left = inputRect.left + scrollLeft - clientLeft;
containerStyle.top = top + "px";
containerStyle.left = left + "px";
maxHeight = window.innerHeight - (inputRect.top + input.offsetHeight);
if (maxHeight < 0) {
maxHeight = 0;
}
containerStyle.top = top + "px";
containerStyle.bottom = "";
containerStyle.left = left + "px";
containerStyle.maxHeight = maxHeight + "px";
}
// the calc method must be called twice, otherwise the calculation may be wrong on resize event (chrome browser)
calc();
calc();
if (settings.customize && inputRect) {
settings.customize(input, inputRect, container, maxHeight);
}
}
/**
* Redraw the autocomplete div element with suggestions
*/
function update() {
// delete all children from autocomplete DOM container
while (container.firstChild) {
container.removeChild(container.firstChild);
}
// function for rendering autocomplete suggestions
var render = function (item, currentValue) {
var itemElement = doc.createElement("div");
itemElement.textContent = item.label || "";
return itemElement;
};
if (settings.render) {
render = settings.render;
}
// function to render autocomplete groups
var renderGroup = function (groupName, currentValue) {
var groupDiv = doc.createElement("div");
groupDiv.textContent = groupName;
return groupDiv;
};
if (settings.renderGroup) {
renderGroup = settings.renderGroup;
}
var fragment = doc.createDocumentFragment();
var prevGroup = "#9?$";
items.forEach(function (item) {
if (item.group && item.group !== prevGroup) {
prevGroup = item.group;
var groupDiv = renderGroup(item.group, inputValue);
if (groupDiv) {
groupDiv.className += " group";
fragment.appendChild(groupDiv);
}
}
var div = render(item, inputValue);
if (div) {
div.addEventListener("click", function (ev) {
settings.onSelect(item, input);
clear();
ev.preventDefault();
ev.stopPropagation();
});
if (item === selected) {
div.className += " selected";
}
fragment.appendChild(div);
}
});
container.appendChild(fragment);
if (items.length < 1) {
if (settings.emptyMsg) {
var empty = doc.createElement("div");
empty.className = "empty";
empty.textContent = settings.emptyMsg;
container.appendChild(empty);
}
else {
clear();
return;
}
}
attach();
updatePosition();
updateScroll();
}
function updateIfDisplayed() {
if (containerDisplayed()) {
update();
}
}
function resizeEventHandler() {
updateIfDisplayed();
}
function scrollEventHandler(e) {
if (e.target !== container) {
updateIfDisplayed();
}
else {
e.preventDefault();
}
}
function keyupEventHandler(ev) {
var keyCode = ev.which || ev.keyCode || 0;
var ignore = [38 /* Up */, 13 /* Enter */, 27 /* Esc */, 39 /* Right */, 37 /* Left */, 16 /* Shift */, 17 /* Ctrl */, 18 /* Alt */, 20 /* CapsLock */, 91 /* WindowsKey */, 9 /* Tab */];
for (var _i = 0, ignore_1 = ignore; _i < ignore_1.length; _i++) {
var key = ignore_1[_i];
if (keyCode === key) {
return;
}
}
if (keyCode >= 112 /* F1 */ && keyCode <= 123 /* F12 */) {
return;
}
// the down key is used to open autocomplete
if (keyCode === 40 /* Down */ && containerDisplayed()) {
return;
}
startFetch(0 /* Keyboard */);
}
/**
* Automatically move scroll bar if selected item is not visible
*/
function updateScroll() {
var elements = container.getElementsByClassName("selected");
if (elements.length > 0) {
var element = elements[0];
// make group visible
var previous = element.previousElementSibling;
if (previous && previous.className.indexOf("group") !== -1 && !previous.previousElementSibling) {
element = previous;
}
if (element.offsetTop < container.scrollTop) {
container.scrollTop = element.offsetTop;
}
else {
var selectBottom = element.offsetTop + element.offsetHeight;
var containerBottom = container.scrollTop + container.offsetHeight;
if (selectBottom > containerBottom) {
container.scrollTop += selectBottom - containerBottom;
}
}
}
}
/**
* Select the previous item in suggestions
*/
function selectPrev() {
if (items.length < 1) {
selected = undefined;
}
else {
if (selected === items[0]) {
selected = items[items.length - 1];
}
else {
for (var i = items.length - 1; i > 0; i--) {
if (selected === items[i] || i === 1) {
selected = items[i - 1];
break;
}
}
}
}
}
/**
* Select the next item in suggestions
*/
function selectNext() {
if (items.length < 1) {
selected = undefined;
}
if (!selected || selected === items[items.length - 1]) {
selected = items[0];
return;
}
for (var i = 0; i < (items.length - 1); i++) {
if (selected === items[i]) {
selected = items[i + 1];
break;
}
}
}
function keydownEventHandler(ev) {
var keyCode = ev.which || ev.keyCode || 0;
if (keyCode === 38 /* Up */ || keyCode === 40 /* Down */ || keyCode === 27 /* Esc */) {
var containerIsDisplayed = containerDisplayed();
if (keyCode === 27 /* Esc */) {
clear();
}
else {
if (!containerDisplayed || items.length < 1) {
return;
}
keyCode === 38 /* Up */
? selectPrev()
: selectNext();
update();
}
ev.preventDefault();
if (containerIsDisplayed) {
ev.stopPropagation();
}
return;
}
if (keyCode === 13 /* Enter */ || (keyCode === 9 /* Tab */ && allowSubmitOnTab)) {
if (selected) {
settings.onSelect(selected, input);
clear();
}
if (preventSubmit) {
ev.preventDefault();
}
}
}
function focusEventHandler() {
if (showOnFocus) {
startFetch(1 /* Focus */);
}
}
function startFetch(trigger) {
// if multiple keys were pressed, before we get update from server,
// this may cause redrawing our autocomplete multiple times after the last key press.
// to avoid this, the number of times keyboard was pressed will be
// saved and checked before redraw our autocomplete box.
var savedKeypressCounter = ++keypressCounter;
var val = input.value;
if (val.length >= minLen || trigger === 1 /* Focus */) {
clearDebounceTimer();
debounceTimer = window.setTimeout(function () {
settings.fetch(val, function (elements) {
if (keypressCounter === savedKeypressCounter && elements) {
items = elements;
inputValue = val;
selected = items.length > 0 ? items[0] : undefined;
update();
}
}, 0 /* Keyboard */);
}, trigger === 0 /* Keyboard */ ? debounceWaitMs : 0);
}
else {
clear();
}
}
function blurEventHandler() {
// we need to delay clear, because when we click on an item, blur will be called before click and remove items from DOM
setTimeout(function () {
if (doc.activeElement !== input) {
clear();
}
}, 200);
}
/**
* Fixes #26: on long clicks focus will be lost and onSelect method will not be called
*/
container.addEventListener("mousedown", function (evt) {
evt.stopPropagation();
evt.preventDefault();
});
/**
* Fixes #30: autocomplete closes when scrollbar is clicked in IE
* See: https://stackoverflow.com/a/9210267/13172349
*/
container.addEventListener("focus", function () { return input.focus(); });
/**
* This function will remove DOM elements and clear event handlers
*/
function destroy() {
input.removeEventListener("focus", focusEventHandler);
input.removeEventListener("keydown", keydownEventHandler);
input.removeEventListener(keyUpEventName, keyupEventHandler);
input.removeEventListener("blur", blurEventHandler);
window.removeEventListener("resize", resizeEventHandler);
doc.removeEventListener("scroll", scrollEventHandler, true);
clearDebounceTimer();
clear();
}
// setup event handlers
input.addEventListener("keydown", keydownEventHandler);
input.addEventListener(keyUpEventName, keyupEventHandler);
input.addEventListener("blur", blurEventHandler);
input.addEventListener("focus", focusEventHandler);
window.addEventListener("resize", resizeEventHandler);
doc.addEventListener("scroll", scrollEventHandler, true);
return {
destroy: destroy
};
}
return autocomplete;
})));
//# sourceMappingURL=autocomplete.js.map