-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocationcomplete.js
605 lines (494 loc) · 21.9 KB
/
locationcomplete.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
(function($, window, undefined) {
'use strict';
var index = 1;
$.fn.locationComplete = function( options, callback ) {
var $input = this;
var value = $input.val();
var searchInterval;
var searchData = null;
var clickedOnResults = false;
var id = "lcmplt" + index;
index ++;
// Define defaults
var defaults = {
limit : 10, // Limit results displayed
interval : 100, // Interval to check for changes in the input
postCodeIndex : 0, // Postcode column in csv
stateIndex : 2, // State column in csv (-1 if not defined)
placeIndex : 1, // Place column in csv
maxHeight : 200, // Maximun height of results element
searchAfter : 2, // Only search after this amount of letters is typed
resultsElement : 'ul', // Container to hold results list
resultElement : 'li', // Container to hold result
resultsClass : 'lc-results-container', // Class of container
resultClass : 'lc-result-item',
loadingMessage : 'Loading locations...',
appendTo : false,
noBlurClass : false
};
// Error will be thrown if these arent defined
var required = ['url'];
var settings = $.extend(defaults, options);
var $parent = settings.appendTo ? $input.closest(settings.appendTo) : $input.parent();
// Count amount of columns
var termsAmount = 0;
if(settings.postCodeIndex >= 0) termsAmount ++;
if(settings.stateIndex >= 0) termsAmount ++;
if(settings.placeIndex >= 0) termsAmount ++;
function init() {
var i = required.length;
// Check to see if required settings are defined.
while( i-- ) {
if(!settings[required[i]]) {
console.error( 'Error: ' + required[i] + ' is not defined' );
return;
}
}
// Basic loading message
$input.data('placeholder', $input.attr('placeholder'));
$input.attr('placeholder', settings.loadingMessage);
$input.attr('autocomplete', 'off');
loadData();
}
/*=================================
= LOAD DATA =
=================================*/
function loadData() {
// Check to see if localstorage is available and contains the correct postcode data.
if(localStorageExists() && localStorage.getItem("postcodeDataURL") === settings.url) {
parseData(localStorage.getItem("postcodeData"));
} else {
// Otherwise ajax in the postcode data.
$.ajax({
url : settings.url,
success : parseData,
error : function() {
console.error( 'Error: Data load failed' );
}
});
}
}
/*==================================
= PARSE DATA =
==================================*/
function parseData(data) {
// Save data & URL
if(localStorageExists()) {
localStorage.setItem("postcodeData", data);
localStorage.setItem("postcodeDataURL", settings.url);
}
var locations = data.split('\n');
var i = locations.length;
var parsed = [];
// If data doesn't use unix line endings then splitting at \n won't work.
if(i === 1) {
console.error('Error: error parsing csv, check line endings - they should be unix');
return;
}
while(i--) {
var datum = {};
// Save full value for exact string matching
datum.value = locations[i];
// Split CSV into columns
var columns = locations[i].split(',');
// Create an array of search tokens from the columns
datum.tokens = columns[settings.placeIndex]
.split(' ')
.concat([
columns[settings.postCodeIndex],
columns[settings.stateIndex]
]).filter(function(token){
return !!token;
});
parsed.push(datum);
}
// Save to global variable and start search
searchData = parsed;
setupSearch();
}
/*==========================================
= SEARCH ON INTERVAL =
==========================================*/
function setupSearch(data) {
// Bind events so that we search when input is focused
$input.on('focus', startSearch);
$input.on('blur', stopSearch);
// Return placeholder to original value, now that everything is loaded
$input.attr('placeholder', $input.data('placeholder') || "");
// If user has already clicked in input before the data was ready, we should search now.
if($input.is(":focus")) {
startSearch();
}
if(callback) {
callback($input);
}
// Start drawing results to bind key events.
drawResults([]);
}
function startSearch() {
searchLocations(true);
// Because of some keyup problems on mobile devices we are searching on an interval instead.
searchInterval = setInterval(searchLocations, settings.interval);
}
function stopSearch() {
// Don't hide if we've clicked on results.
if(!clickedOnResults) {
// Hide dropdown and clear interval when we blur out.
$('#' + id).hide();
clearInterval(searchInterval);
}
}
/*==============================
= SEARCH =
==============================*/
function searchLocations(initialFocus) {
// Only search if input has changed
if($input.val() === value && !initialFocus) return;
var searchValue = $input.val().toLowerCase();
// Only search if more than min letters is typed
if(searchValue.length <= settings.searchAfter) {
// Hide dropdown if less than min letters typed
if($('.'+settings.resultClass).length > 0) {
drawResults([]);
value = $input.val();
}
return;
}
// If there are 3 commas in the search string then it is
// safe to assume that the field has been autofilled,
// so there is no need to search
if(searchValue.split(',').length > 2) {
// Hide dropdown
if($('.'+settings.resultClass).length > 0) {
drawResults([]);
value = $input.val();
}
return;
}
// Separate out search term into an array of tokens.
var searchValues = searchValue.split(' ');
var results = [];
// SEARCH
var i = searchData.length;
// Loop through each location
while(i --) {
var match = false;
var matchWeight = 0;
var k = searchValues.length;
// Loop through each search term
while(k--) {
// Make sure that search term is not empty
if(searchValues[k].length > 1) {
// Check if any search term exists in location at all
if(searchData[i].value.indexOf(searchValues[k]) !== - 1) {
match = true;
// If it does then loop through the tokens to see how
// many matches there are and generate a search weight
var tokens = [].concat(searchData[i].tokens);
var j = tokens.length;
while( j -- ) {
var strIndex = tokens[j].indexOf(searchValues[k]);
if(strIndex !== -1) {
// Count as match and increment
matchWeight += 2;
// If input string is directly matched in data string, add extra weight
if(searchData[i].value.indexOf(searchValue) !== -1) {
matchWeight ++;
}
// If indexs are the same between search and token, add 1 weight
if(j === k) {
matchWeight ++;
}
// Give extra weight if search string is near start of token
matchWeight += (4 / (strIndex + 1));
// Give extra weight based on how close string is to an exact match
matchWeight += (searchValues[k].length / tokens[j].length) * 2;
// Give one extra weight for exact matches
if(searchValues[k] === tokens[j]) {
matchWeight ++;
}
tokens[j] = "";
// We don't want to match the search term to multiple tokens so stop here if there's a match.
break;
}
}
}
} else {
// Low complexity search for search terms of only one letter.
if(searchValue.length > 1 && searchData[i].value.indexOf(searchValue) !== -1) {
matchWeight += 3;
}
}
}
if(match) {
// Base weight on how close to exact string we get
var weight = matchWeight / (searchData[i].tokens.length / searchValues.length);
results.push([searchData[i].value, weight]);
}
}
// Sort results based on weight
results = results.sort(function(a,b){
return a[1] < b[1] ? 1 : -1;
});
// Limit results
results = results.slice(0, settings.limit);
value = $input.val();
drawResults(results);
}
/*====================================
= DRAW RESULTS =
====================================*/
function drawResults(results) {
var $container = $('#'+id);
var containerExists = $container.length > 0;
// Check if container exists and if so make $container equal to it, if not, create new container.
$container = containerExists ? $container : $('<'+settings.resultsElement+' style="max-height:'+settings.maxHeight+'px; overflow-y: auto;"/>').addClass(settings.resultsClass).attr('id', id);
// Loop through results and generate html output.
var html = '';
for ( var i = 0; i < results.length; i ++ ) {
var sections = results[i][0].split(',');
var postcode = (sections[settings.postCodeIndex] || '');
var place = toTitleCase((sections[settings.placeIndex]) || '');
var state = (sections[settings.stateIndex] || '').toUpperCase();
var focused = i === 0 ? 'lc-focused' : '';
var value = [place, state, postcode].filter(function(item){
return !!item;
}).join(', ');
html += '<'+ settings.resultElement +' class="'+settings.resultClass+' '+focused+'">';
html += value;
html += '</'+settings.resultElement+'>';
}
// Empty container and scroll to top.
$container.empty().html(html).scrollTop(0);
// If container doesn't exist, add it to the page.
if(!containerExists) {
if(settings.appendTo) {
$parent.append($container);
} else {
$input.after($container);
}
bindEvents($container);
} else {
$container.show();
}
}
/*===================================
= BIND EVENTS =
===================================*/
function bindEvents($elem) {
var $container = $elem;
// Add focused class on hover
$container.on('mouseenter mouseleave', '.'+settings.resultClass, function(e) {
$parent.find('.lc-focused').removeClass('lc-focused');
$(this).toggleClass('lc-focused');
});
// Select item on click
$container.on('click', '.'+settings.resultClass, function(e) {
$parent.find('.lc-focused').removeClass('lc-focused');
$(this).toggleClass('lc-focused');
selectItem(e, $input[0]);
});
// This is a fix for an IE8 bug where clicking on the scroll bar of the results
// dropdown causes the blur to trigger and the dropdown to close.
$container.on('mousedown touchstart', function(e) {
clickedOnResults = true;
});
// If focus moves from results container to anywhere else then close container
// and return focus to input.
$('html').on('click.' + id, function(e) {
var $target = $(e.target);
var $nearestparent = $target.closest($parent);
if(settings.noBlurClass && $target.hasClass(settings.noBlurClass)) {
// Don't hide results
} else if($nearestparent.length === 0) {
clickedOnResults = false;
drawResults([]);
}
});
// Bind Key Events
$input.on('keydown', function(e) {
switch(e.keyCode) {
case 38 : // Up
focusPrev(e, this);
break;
case 40 : // Down
focusNext(e, this);
break;
case 13: // Enter
case 9 : // tab
selectItem(e, this);
break;
default:
return;
}
var $new = $parent.find('.lc-focused');
if($new.length === 0) return;
// Make sure that selected item stays in middle of scrolling box.
var current = $new.offset().top;
var desired = ($elem.height() / 2) - ($new.height() / 2) + $elem.offset().top - $elem.scrollTop();
var delta = current - desired;
if(delta > 0) {
$elem.scrollTop(delta);
} else {
$elem.scrollTop(0);
}
});
}
function focusPrev(e, elem) {
// Focus previous element
if(elem.value.length <= settings.searchAfter) {
return;
}
e.preventDefault();
var $focused = $parent.find('.lc-focused');
$focused.removeClass('lc-focused');
var $prev = $focused.prev();
if($focused.length === 0 || $prev.length === 0) {
$('.'+settings.resultClass).last().addClass('lc-focused');
} else {
$prev.addClass('lc-focused');
}
}
function focusNext(e, elem) {
// Focus next element
if(elem.value.length <= settings.searchAfter) {
return;
}
e.preventDefault();
var $focused = $parent.find('.lc-focused');
$focused.removeClass('lc-focused');
var $next = $focused.next();
if($focused.length === 0 || $next.length === 0) {
$('.'+settings.resultClass).first().addClass('lc-focused');
} else {
$next.addClass('lc-focused');
}
}
function selectItem(e, elem) {
// Select element
var $focused = $parent.find('.lc-focused');
if(!$focused || $focused.length === 0) {
$input.trigger("locationcomplete:failedsearch", [$input.val()]);
return;
}
if(elem.value === $focused.text() || elem.value.length < settings.searchAfter) {
return;
}
if(e) {
e.preventDefault();
}
if($focused.length === 0) {
$focused = $('.'+settings.resultClass).first();
}
$input.val($focused.text());
// Don't trigger on tab press
if(e && e.keyCode !== 9) {
// Trigger selected event
$input.trigger("locationcomplete:select", [$focused.text()]);
}
searchLocations();
drawResults([]);
}
/*================================================================
= Method to validate location against data =
================================================================*/
this.validate = function(string) {
// Don't validate if search data isn't loaded - leave that to the backend
if(!searchData) {
return true;
}
var value = string || $input.val();
var terms = value.toLowerCase().split(',');
// There should be three terms in a valid location
if(terms.length !== termsAmount) {
return false;
}
var placeIndex = settings.placeIndex >= 0 ? 0 : -1;
var stateIndex = settings.stateIndex >= 0 ? (
settings.placeIndex >= 0 ? 1 : 0
) : -1;
var postCodeIndex = settings.postCodeIndex >= 0 ? (
settings.placeIndex >= 0 ? (
settings.stateIndex >= 0 ? 2 : 1
) : (
settings.stateIndex >= 0 ? 1 : 0
)
) : -1;
var place = $.trim(terms[placeIndex]);
var state = $.trim(terms[stateIndex]);
var postcode = $.trim(terms[postCodeIndex]);
var ordered = [];
if(place)
ordered[settings.placeIndex] = place;
if(state)
ordered[settings.stateIndex] = state;
if(postcode)
ordered[settings.postCodeIndex] = postcode;
var search = ordered.join(',');
var i = searchData.length;
var match = false;
while(i--) {
if(searchData[i].value === search){
match = true;
}
}
return match;
};
this.destroy = function() {
var $container = $('#'+id);
// unbind events
$input.off('focus');
$input.off('blur');
$input.off('keydown');
$container.off('mouseenter mouseleave');
$container.off('click');
$container.off('mousedown touchstart');
$container.remove();
// If focus moves from results container to anywhere else then close container
// and return focus to input.
$('html').off('click.' + id);
};
this.select = function() {
selectItem(null, $input[0]);
};
/*========================================
= HELPER FUNCTIONS =
========================================*/
// Allow console to work in IE8
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// Test if localstorage is available
function localStorageExists() {
try {
localStorage.setItem('test', 'testing');
localStorage.removeItem('test');
return true;
} catch(e) {
return false;
}
}
// Convert string to title case
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
init();
return this;
};
})(jQuery, window);