This repository has been archived by the owner on Nov 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
autocomplete.js
483 lines (387 loc) · 11.5 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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import {computedFrom, inject, bindable, bindingMode} from "aurelia-framework";
import {Config} from "aurelia-api";
import {logger} from "../aurelia-autocomplete";
import {DOM} from "aurelia-pal";
import {resolvedView} from "aurelia-view-manager";
@resolvedView('spoonx/auto-complete', 'autocomplete')
@inject(Config, DOM.Element)
export class AutoCompleteCustomElement {
lastFindPromise;
// the query string is set after selecting an option. To avoid this
// triggering a new query we set the justSelected to true. When true it will
// avoid performing a query until it is toggled of.
justSelected = false;
// Holds the value last used to perform a search
previousValue = null;
// Simple property that maintains if this is the initial (first) request.
initial = true;
dropdownToggle;
dropdownMenu;
hasFocus = false;
// How many characters are required to type before starting a search.
@bindable minInput = 0;
// the name of the input element
@bindable name = '';
// The max amount of results to return. (optional)
@bindable limit = 10;
// Debounce value
@bindable debounce = 100;
// The string that is appended to the api endpoint. e.g. api.com/language. language is the resource.
@bindable resource;
// Used when one already has a list of items to filter on. Requests is not necessary
@bindable items;
// The string to be used to do a contains search with. By default it will look if the name contains this value.
@bindable({defaultBindingMode: bindingMode.twoWay}) value = '';
// Can be used to select default element visually
@bindable selected;
// The property to query on.
@bindable attribute = 'name';
// Used to pass the result of the selected value to the user's view model
@bindable({defaultBindingMode: bindingMode.twoWay}) result = null;
// The results returned from the endpoint. These can be observed and mutated.
@bindable({defaultBindingMode: bindingMode.twoWay}) results = [];
// Which relations to populate for results
@bindable populate = null;
// The label to show in the footer. Gets pulled through aurelia-i18n.
@bindable footerLabel = 'Create';
// Callback to call when the footer gets clicked.
@bindable footerSelected;
// Never, always or no-results
@bindable footerVisibility = 'never';
// Used to determine the string to be shown as option label
@bindable label = result => {
let defaultAttribute = Array.isArray(this.attribute) ? this.attribute[0] || 'name' : this.attribute;
return typeof result === 'object' && result !== null ? result[defaultAttribute] : result;
};
// Allow to overwrite the default apiEndpoint
@bindable endpoint;
// Input field's placeholder
@bindable placeholder = 'Search';
// Sort method that takes a list and returns a sorted list. No sorting by default.
@bindable sort = items => items;
// Used to make the criteria more specific
@bindable criteria = {};
@computedFrom('results', 'value')
get showFooter() {
let visibility = this.footerVisibility;
return visibility === 'always'
|| (visibility === 'no-results' && this.value && this.value.length && (!this.results || !this.results.length));
}
showDropdown() {
if (!this.dropdownMenu.hasClass('show')) {
this.dropdownToggle.dropdown('toggle');
}
}
/**
* Autocomplete constructor.
*
* @param {Config} api
* @param {Element} element
*/
constructor(api, element) {
this.element = element;
this.apiEndpoint = api;
}
/**
* Bind callback.
*
* @returns {void}
*/
bind() {
if (!this.resource && !this.items) {
return logger.error('auto complete requires resource or items bindable to be defined');
}
this.value = this.label(this.result);
if (this.apiEndpoint) {
this.apiEndpoint = this.apiEndpoint.getEndpoint(this.endpoint);
}
this.dropdownToggle = $(this.dropdownToggle);
this.dropdownMenu = $(this.dropdownToggle.parent().find('.dropdown-menu')[0]);
}
/**
* Set focus on dropdown.
*
* @param {boolean} value
* @param {Event} [event]
*
* @returns {boolean}
*/
setFocus(value, event) {
function isDescendant(parent, child) {
let node = child.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
// If descendant, don't toggle dropdown so that other listeners will be called.
if (event && event.relatedTarget && isDescendant(this.element, event.relatedTarget)) {
return true;
}
if (value) {
return this.valueChanged();
}
this.hasFocus = value;
}
/**
* returns HTML that wraps matching substrings with strong tags.
* If not a "stringable" it returns an empty string.
*
* @param {Object} result
*
* @returns {String}
*/
labelWithMatches(result) {
let label = this.label(result);
if (typeof label !== 'string') {
return '';
}
return label.replace(this.regex, match => {
return `<strong>${match}</strong>`;
});
}
/**
* Handle keyUp events from value.
*
* @param {Event} event
*
* @returns {*}
*/
handleKeyUp(event) {
if (event.keyCode !== 27) {
return;
}
if (this.hasFocus) {
event.stopPropagation();
}
this.setFocus(false);
return true;
}
/**
* Handle keyDown events from value.
*
* @param {Event} event
*
* @returns {*}
*/
handleKeyDown(event) {
if (event.keyCode === 27) {
return;
}
if (event.keyCode === 40 || event.keyCode === 38) {
this.selected = this.nextFoundResult(this.selected, event.keyCode === 38);
return event.preventDefault();
}
if (event.keyCode === 9 || event.keyCode === 13) {
if (this.hasFocus) {
event.stopPropagation();
event.preventDefault();
}
if (this.results.length !== 0 && this.hasFocus) {
this.onSelect();
}
} else if (event.keyCode !== 37 && event.keyCode !== 39) {
// ensure dropdown is uncollapsed when there are results while user types
if (this.results.length > 0) {
this.showDropdown();
}
this.setFocus(true);
}
return true;
}
/**
* Get the next result in the list.
*
* @param {Object} current selected item
* @param {Boolean} [reversed] when true gets the previous instead
*
* @returns {Object} the next of previous item
*/
nextFoundResult(current, reversed) {
let index = (this.results.indexOf(current) + (reversed ? -1 : 1)) % (this.results.length);
if (index < 0) {
index = this.results.length - 1;
}
return this.results[index];
}
/**
* Set the text in the input to that of the selected item and set the
* selected item as the value. Then hide the results(dropdown)
*
* @param {Object} [result] when defined uses the result instead of the this.selected value
*
* @returns {boolean}
*/
onSelect(result) {
result = (arguments.length === 0) ? this.selected : result;
this.justSelected = true;
this.value = this.label(result);
this.previousValue = this.value;
this.selected = result;
this.result = result;
this.setFocus(false);
return true;
}
resultChanged() {
if (this.selected !== this.result) {
this.onSelect(this.result);
}
}
/**
* when search string changes perform a request, assign it to results
* and select the first result by default.
*
* @returns {Promise}
*/
valueChanged() {
let initial = this.initial;
if (!this.shouldPerformRequest()) {
this.previousValue = this.value;
this.hasFocus = !initial && !(this.results.length === 0);
return Promise.resolve();
}
this.result = null;
if (!this.hasEnoughCharacters()) {
this.results = [];
this.previousValue = this.value;
this.hasFocus = false;
return Promise.resolve();
}
this.hasFocus = true;
// when resource is not defined it will not perform a request. Instead it
// will search for the first items that pass the predicate
if (this.items) {
this.results = this.sort(this.filter(this.items));
return Promise.resolve();
}
let lastFindPromise = this.findResults(this.searchQuery(this.value))
.then(results => {
if (this.lastFindPromise !== lastFindPromise) {
return;
}
this.previousValue = this.value;
this.lastFindPromise = false;
this.results = this.sort(results || []);
if (this.results.length !== 0) {
this.selected = this.results[0];
}
});
this.lastFindPromise = lastFindPromise;
}
/**
* returns a list of length that is smaller or equal to the limit. The
* default predicate is based on the regex
*
* @param {Object[]} items
*
* @returns {Object[]}
*/
filter(items) {
let results = [];
items.some(item => {
// add an item if it matches
if (this.itemMatches(item)) {
results.push(item);
}
return (results.length >= this.limit)
});
return results;
}
/**
* returns true when the finding of matching results should continue
*
* @param {*} item
*
* @return {Boolean}
*/
itemMatches(item) {
return this.regex.test(this.label(item));
}
@computedFrom('value')
get regex() {
return new RegExp(this.value, 'gi');
}
/**
* returns true when a request will be performed on a search change
*
* @returns {Boolean}
*/
shouldPerformRequest() {
if (this.justSelected === true) {
this.justSelected = false;
return false;
}
if (this.initial) {
this.initial = false;
return false;
}
return this.value !== this.previousValue;
}
/**
* Returns whether or not value has enough characters (meets minInput).
*
* @returns {boolean}
*/
hasEnoughCharacters() {
return ((this.value && this.value.length) || 0) >= this.minInput;
}
/**
* @param {Object} query a waterline query object
*
* @returns {Promise} which resolves to the found results
*/
findResults(query) {
return this.apiEndpoint.find(this.resource, query)
.catch(err => logger.error('not able to find results', err));
}
/**
* Emit custom event, or call function depending on supplied value.
*
* @param {string} value
*/
onFooterSelected(value) {
if (typeof this.footerSelected === 'function') {
this.footerSelected(value);
return;
}
this.element.dispatchEvent(
DOM.createCustomEvent('footer-selected', {detail: {value}})
);
}
/**
* Takes a string and converts to to a waterline query object that is used to
* perform a forgiving search.
*
* @param {String} string the string to search with
*
* @returns {Object} a waterline query object
*/
searchQuery(string) {
let ors = [];
let where;
if (Array.isArray(this.attribute)) {
this.attribute.forEach(attribute => {
ors.push({[attribute]: {contains: string}});
});
} else {
where = {[this.attribute]: {contains: string}};
}
let mergedWhere = Object.assign(
Array.isArray(this.attribute) ? {or: ors} : where,
this.criteria
);
let query = {
populate: this.populate || 'null',
where : mergedWhere
};
// only assign limit to query if it is defined. Allows to default to server
// limit when limit bindable is set to falsy value
if (this.limit) {
query.limit = this.limit;
}
return query;
}
}