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
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
body { font-family: 'Cantarell', Helvetica, Arial, sans-serif; margin: 2em; }
.twitter-typeahead { width: 87%; }
.typeahead, .tt-query, .tt-hint {
width: 100%; height: 30px;
padding: 8px 12px; outline: none;
font-size: 20px; line-height: 30px;
border: 2px solid #ccc; border-radius: 8px;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
}
.tt-menu {
width: 100%; margin: 12px 0; padding: 8px 0;
background-color: #fff;
border: 1px solid #ccc; border-radius: 8px;
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
-webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
-moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.tt-suggestion { padding: 3px 20px; line-height: 24px; font-size: 18px; }
.tt-suggestion:hover { cursor: pointer; }
.tt-suggestion span { padding-left: 16px; font-size: 14px; color: #777; float: right; }
.tt-cursor { background: #ddd; }
.tt-highlight { font-weight: normal; color: #777; }
.tt-hint { color: #9598; }
#selections { width: 87%; padding-top: 40px; }
#selections div { padding: 4px 40px; line-height: 24px; font-size: 18px; color: #666; }
#selections div span { padding-left: 16px; font-size: 14px; color: #999; float: right; }
.-info- { font-size: 12px !important; color: #959 !important;
font-family: 'JetBrains Mono NL', Consolas, Monaco, monospace, fixed !important;
line-height: 14px !important; border-bottom: 1px solid #ddda;
}
.-info- b { font-weight: 900; }
</style>
<!-- js labraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/corejs-typeahead/1.2.1/bloodhound.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/corejs-typeahead/1.2.1/typeahead.jquery.min.js"></script>
</head>
<body>
<div id="the-basics">
<input class="typeahead" id="tagsInput" type="text" placeholder="try me!">
</div>
<div id="selections">
</div>
</body>
<script>
// PUBLIC VARIABLES ////////////////////////////////////////////////////////////
var _kwlinks; // keyword links (word-connections; imported via ajax-get)
var _products; // all products (imported via ajax-get)
var trackSearch = []; // searching analytics
// setup options
var maxResults = 24; // limit suggestions
var blendProds = 4; // minimum final-produncts to blend with next-word suggestions
var allowFuzzy = false; // enable|disable fuzzy search
var bi1stScore = .65; // bigram minimum match score for 1st word
var bi2ndScore = .85; // bigram minimum match score for 2nd word
var ignoredKeys_kb = []; // keywords to ignore (in kb-format)
['μας με σε για του της των από στο στον &'].split(' ').forEach(w => { ignoredKbs.push(kb_trans(w)); });
// SUPLAMENARY FUNCTIONS ///////////////////////////////////////////////////////
// arrays for kb-format (utf/EL-Gr to ascii translation)
var ORiGiNal = 'ςερτυθιοπασδφγηξκλζχψωβνμΕΡΤΥΘΙΟΠΑΣΔΦΓΗΞΚΛΖΧΨΩΒΝΜάέήίόύώϊϋΆΈΉΊΌΎΏΪΫQWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789-'.split('');
var kbKeyZed = 'sertyuiopasdfghjklzxcvbnmertyuiopasdfghjklzxcvbnmaehioyviyaehioyviyqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm0123456789-'.split('');
const map = new Map();
for (var i=0; i<ORiGiNal.length; i++) map.set(ORiGiNal[i], kbKeyZed[i]);
// function kb_trans
// translates string to keyboard-latin keys;
// [map]'s implementation is 40x faster than [for]'s
function kb_trans(str) {
str = str.replace('\'','');
var out = ''
for (var i=0 ; i< str.length; i++) out += map.get(str[i]);
return out;
}
// pure JS ajax GET request; return data as JSON
// no fancy things like UTF8; if needed use base64
// ---
function ajax_get(url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var data = JSON.parse(xmlhttp.responseText);
} catch(err) {
console.log(err.message + " in " + xmlhttp.responseText);
return;
}
callback(data);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// bigram fuzzy match
// --- credit: https://dirask.com/posts/JavaScript-check-words-similarity-fuzzy-compare-with-bigrams-paola1
const createBigram = word => {
const input = word.toLowerCase();
const vector = [];
for (let i = 0; i < input.length; ++i) {
vector.push(input.slice(i, i + 2));
}
return vector;
};
const checkSimilarity = (a, b) => {
if (!allowFuzzy) return false;
if (a.length > 0 && b.length > 0) {
const aBigram = createBigram(a);
const bBigram = createBigram(b);
let hits = 0;
for (let x = 0; x < aBigram.length; ++x) {
for (let y = 0; y < bBigram.length; ++y) {
if (aBigram[x] === bBigram[y]) {
hits += 1;
}
}
}
if (hits > 0) {
const union = aBigram.length + bBigram.length;
return (2.0 * hits) / union;
}
}
return 0;
};
// compact print of search-tracking
// ---
function echo_tracking() {
var actions = [];
var c;
var chs = 0; // number of characters pressed;
var uis = 0; // number of UI actions used (arrows, enters etc.)
var countingStarted = false; // flag
trackSearch.forEach(e => {
switch(e.v) {
// use of ui actions
case 'ArrowDown' : c = '↓'; uis++; break;
case 'ArrowUp' : c = '↑'; uis++; break;
case 'Enter' : c = '↲ '; uis++; break;
case 'ArrowLeft' : c = '←'; uis++; break;
case 'ArrowRight': c = '→'; uis++; break;
case ' ' : c = '· '; uis++; break;
// ignored keys
case 'Alt' : c = 'Alt'; break;
case 'Control' : c = 'Ctrl'; break;
case 'Escape' : c = 'Esc'; break;
case 'Shift' : c = 'Shft'; break;
case 'Home' : c = 'Home'; break;
case 'End' : c = 'End'; break;
// backspace (user's typing errors)
case 'Backspace' : c = 'BkSp'; break;
case 'Delete' : c = 'Del'; break;
// actual typed characters
default:
if (e.v.length == 1) {
c = '<b><u>'+ e.v +'</u></b>';
chs++;
}
else { // some non important key; no counter increased
c = e.v; // just record the key
}
}
actions.push(c);
});
return actions.join(',') +' (<u>'+ chs +' chs</u>, '+ uis +' uis)';
}
// workline object to track status of async svents
// ---
var workline = {
trackerJL : 0,
set jsonLoaded(x) {
this.trackerJL = x;
// fire event on certain values
if (x == 2) {
console.log('All streams loaded');
// code to execute
// ...
}
},
get jsonLoaded() { return this.trackerJL; }
};
// LOAD DATA ///////////////////////////////////////////////////////////////////
ajax_get('results/keywords-v3.json', function(data) {
_kwlinks = data;
workline.jsonLoaded++; console.log('keywords loaded');
});
ajax_get('results/products.json', function(data) {
_products = data;
workline.jsonLoaded++; console.log('products loaded')
});
// on document ready code ///////////////////////////////////////////////////////
$(document).ready(function() {
// suggestions engine //////////////////////////////////////////////////////
// ---
function suggestions_engine(qOrig) {
var results = []; // suggestions to respond
var proList = []; // list of products (for all suggestions)
var commonL = []; // list of common products (for multiple suggestions)
var possibleNext = []; // list of possible next suggestions
var root, last;
// clean q(uery) string from symbols and multiple spaces
var q = qOrig.replace('+',' ').replace('.',' ')
.replace(' ',' ')
.replace(' ',' ');
var qAr = q.split(' '); // split to words
if (qAr.length == 1) { // suggest 1st word ////////////////////////
var kbq = kb_trans(q)
// ### (-) regex match all possible suggestions; (in kb-format)
// ### (-) substrRegex = new RegExp( kbq, 'i'); // match q anywhere
_kwlinks.forEach( it => {
// ### (-) if ( (substrRegex.test(it.kb))
if ( (it.kb.indexOf(kbq) !== -1)
|| (checkSimilarity(it.kb, kbq) > bi1stScore) ) {
// a match found
results.push(it);
// also get possible products
// (but only if products are less max-results)
if (proList.length < maxResults + 2) {
it.c.forEach( wo => { proList = proList.concat(wo.p); });
// keep unique products in the list
proList = proList.filter((item, i, ar) => ar.indexOf(item) === i);
}
}
});
}
if (qAr.length == 2) { // suggest 2nd word ///////////////////////////
root = qAr[0].trim();
kbroot = kb_trans(root);
// ### (-) substrRegex = new RegExp( kb_trans(qAr[1]), 'i');
_kwlinks.forEach( it => { // loop through suggestions
if (it.kb == kbroot ) { // match 1st suggestion
it.c.forEach ( wo => { // regex match linked words
// ### (-) if ( (substrRegex.test(wo.kb))
if ( (wo.kb.indexOf(qAr[1]) !== -1)
|| (checkSimilarity(wo.kb, kbroot) > bi2ndScore) ) {
results.push({
w: root +' '+ wo.w,
f: 100
});
proList = proList.concat(wo.p)
}
});
}
});
}
if (qAr.length > 2) {
root = qAr.shift(); // get out the first item of tempQAr
last = qAr.pop(); // get out the lase item of qAr
// now qAr includes only the items after root and before last;
// so qAr includes all already selected suggestions (but root)
// prepare/cache kb-formats for any key we may need
// ---
var kbqAr = []; // array of selected suggestions in kb-format
qAr.forEach( w => { kbqAr.push(kb_trans(w)); })
// kb-translate the root/last keys too
kbroot = kb_trans(root);
kblast = kb_trans(last);
// ### (-) substrRegex = new RegExp( kblast, 'i'); // construct regex for mathing
_kwlinks.forEach( it => {
if (it.kb == kbroot ) { // find root
// calculate list of common items/products (commonL)
// for selected suggestions
// ---
is1stOcc = true; // 1st occurance flag
it.c.forEach ( swo => {
if (kbqAr.indexOf( swo.kb ) !== -1) {
// swo is one of the already selected suggestions
// so...
// update the commonL(ist)
if (is1stOcc) {
commonL = swo.p; // init list (on 1st occurance)
is1stOcc = false;
}
else {
// caclulate list of common products
// = intersection of (so-far) commonL and swo.p
// commonL = commonL.filter(value => swo.p.includes(value));
commonL = commonL.filter(function(n) { return swo.p.indexOf(n) !== -1; });
}
}
else { // if swo is not already selected
// then it is a possible next suggestion
possibleNext.push(swo);
}
});
possibleNext.forEach( poss => { // for tthe possible next suggestions
// if word matches regex
// and list of word's products has commons with commonL
// then it is a valid next suggestion
if (poss.kb.indexOf(kblast) !== -1 ) {
// check intersection of commonL and suggestion's product-lists
tempL = commonL.filter(value => poss.p.includes(value));
if (tempL.length) {
results.push({
w: root +' '+ qAr.join(' ') +' '+ poss.w,
f: 100
});
// update proList too
proList = proList.concat(tempL)
}
}
});
}
});
}
// calculate unique products
let unique = proList.filter((item, i, ar) => ar.indexOf(item) === i);
// credit: https://stackoverflow.com/questions/11246758/
// console.log(q, qAr, qAr.length, proList.length);
if (unique.length < (maxResults +1)) {
results = [];
unique.forEach( pr => {
_products.forEach( pi => {
if (pi.id == pr)
results.push(pi);
})
});
}
return results;
}
// request suggestions procedure
// args...
// qOrig: original query string
// list: artay structure to host results
// ---
var isuggest = function(qOrig, list) {
var results = suggestions_engine(qOrig);
// if no results...
// request again after removing last (key)word
if (results.length == 0) {
var qAr = qOrig.trim().split(' ');
qAr.pop(); // remove last word
results = suggestions_engine(qAr.join(' '));
}
list(results);
}
// setup suggestions search/input control
// ---
const $tagsInput = $('#tagsInput')
$tagsInput.typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
limit: maxResults,
name: 'kwlinks',
displayKey: 'w',
source: isuggest,
templates: {
suggestion: function(data) {
// console.log(data.w);
if (data.id)
return '<div>'+ data.w + '<span>' + data.id + '</span></div>';
return '<div>'+ data.w +'<span>+</span></div>';
}
}
}
)
.bind("typeahead:selected", function(obj, datum, name) {
// console.log(datum);
if (datum.hasOwnProperty('id')) {
// final product selected; do whatever ...
// ex. add to selection list
$('#selections').append('<div>'+ datum.w + '<span>' + datum.id + '</span></div>');
// then reset search control
$('.typeahead').typeahead('val','').trigger('blur')
.trigger("query");
setTimeout(() => { $('.typeahead').focus(); }, 100);
// finaly save tracking info;
$('#selections').append('<div class="-info-">'+ echo_tracking() +'</div>');
trackSearch.length = 0; // ... and reset info to be ready for nextsearch
}
else {
$('.typeahead').typeahead('val','').trigger('blur');
$('.typeahead').typeahead('val', datum.w +' ')
.trigger("query");
// give some time to the engine to calculate results
// then fire focus again...
setTimeout(() => { $('.typeahead').focus(); }, 100);
}
trackSearch.push({
e: 'key',
v: 'Enter',
i: $('#tagsInput').val()
});
})
.bind("typeahead:cursorchange", function(obj, data) {
// console.log(obj, data);
// var dt = new Date();
// console.log('triggered cursorchange /'+dt);
});
// TRACK user search attempt ///////////////////////////////////////////////
$('.typeahead').on('keyup', function(e) {
trackSearch.push({
e: 'key',
v: e.key,
i: $('#tagsInput').val()
});
});
});
// also check (for suearching benchmarks)
// ---
// https://www.measurethat.net/Benchmarks/Show/13675/0/regextest-vs-stringincludes-vs-stringmatch
// https://stackoverflow.com/questions/5296268/fastest-way-to-check-a-string-contain-another-substring-in-javascript
// https://stackoverflow.com/questions/40387106/string-startwith-vs-regex
// https://www.measurethat.net/Benchmarks/Show/4797/1/js-regex-vs-startswith-vs-indexof
</script>
</html>
|