-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
467 lines (426 loc) · 17.9 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8" />
<title>Tiny Type Ahead</title>
<script type="text/javascript" src="resources/stuquery.js"></script>
<script src="resources/highlight.pack.js" type="text/javascript"></script>
<style>
body {
font-family: 'Trebuchet MS',Tahoma,Helvetica,Verdana,sans-serif;
color: black;
margin: 0px;
padding: 0px;
background-color: white;
line-height: 1.5em;
}
header, .content {
max-width: 940px;
display: block;
margin:auto;
position: relative;
color: #444;
padding: 1em;
}
header {
padding-top: 3em;
}
#downloads { background: #f8f8f8; padding: 1em; position: relative; right: 0px; }
#downloads li { margin-left: 1em; }
#downloads a { padding-right: 0.5em; }
a, a:visited { color: #0090FF; }
#forkme_banner {
background: url("https://slowe.github.io/graph/images/blacktocat.png") no-repeat scroll 95% 50% #0090FF;
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
color: #FFFFFF;
display: block;
font-weight: 700;
padding: 10px 50px 10px 10px;
position: absolute;
right: 1em;
top: 0em;
z-index: 10;
text-decoration: none;
}
.version { font-size: 0.6em; position: relative; padding-left: 0.5em; }
.version:before { content: "v"; }
code { background-color: #f8f8f8; padding: 0.25em; }
li.example { margin-bottom: 4em; }
h1 { margin-top: 0px; }
h2 { margin-top: 2em; padding-top: 1em; font-size: 1.5em; }
h3 { font-size: 1.4em; }
h4 { font-size: 1.2em; }
.content h2 { margin-top: 0px; border-top: 0px; }
input { font-size: inherit; padding: 0; box-sizing: border-box; }
input[type="text"] { display: inline-block; height: 2em; border: 1px solid #999; border-radius: 0px; padding-left: 0.5em; max-width: calc(100% - 4.2em); }
input[type="submit"] { height: 2em; padding: 0px 0.5em; border: 0px; background: #444; color: white; cursor: pointer; }
input[type="submit"]:hover, input[type="submit"]:focus { background: #0090FF; color: white; }
label { font-weight: bold; }
#form { background: #f8f8f8; padding: 1em; }
#form ol li > a { background: #efefef; }
#form ol li.selected > a { background: #0090FF; }
#form ol li > a:hover, #form ol li > a:focus { background: #444; color: white; }
.prettyprint { line-height: 1.25em; }
.hljs { background: #f8f8f8; padding: 1em; display:block; overflow-x:auto; margin: 1em auto; tab-size: 4; -moz-tab-size: 4; }
.hljs a { color: inherit; }
.hljs, .hljs-subst { color: black; }
.hljs-name, .hljs-tag { color: #0090FF; }
.hljs-string { color: #65B042; }
.hljs-meta, .hljs-symbol, .hljs-template-tag, .hljs-template-variable, .hljs-addition { color:#0DBC37; }
.hljs-comment, .hljs-quote { color:#999; }
.hljs-number, .hljs-built_in { color: #0090FF; }
.hljs-regexp, .hljs-literal, .hljs-bullet, .hljs-link { color:#31a354; }
.hljs-deletion, .hljs-variable { color:#88f; }
.hljs-selector-tag, .hljs-title, .hljs-section, .hljs-doctag, .hljs-type, .hljs-selector-id, .hljs-selector-class, .hljs-strong { color:#0090FF; }
.hljs-keyword { color: #E28964; }
.hljs-emphasis { font-style:italic; }
.hljs-attribute { color:#D73058; }
.hljs-attr { color: #bdb76b; }
.results{ margin-top: 1em; border: 1px dashed black; padding: 0.5em;}
</style>
</head>
<body>
<header>
<a href="https://github.com/slowe/TinyTypeAhead" id="forkme_banner">Fork Me on GitHub</a>
<h1>Tiny Type-ahead<span class="version"></span></h1>
<p>A tiny, lightweight, dependency-free, type-ahead search to attach to input fields.</p>
<form id="form">
<label for="typeahead0">Search for a UK airport:</label><br />
<input type="text" id="typeahead0" value="" placeholder="e.g. Leeds and Bradford" />
<div class="results">
The result is: <span id="results"></span>
</div>
</form>
</header>
<div class="content">
<h2>Downloads</h2>
<ul id="downloads">
<li><a href="resources/typeahead.js" class="file">typeahead.js (kB)</a></li>
<li><a href="resources/typeahead.min.js" class="file">typeahead.min.js (kB)</a></li>
<li><a href="resources/typeahead.css" class="file">typeahead.css (kB)</a></li>
</ul>
<script>
function ready(f){
if(/in/.test(document.readyState)) setTimeout('S(document).ready('+f+')',9);
else f();
};
var files = S('.file');
for(var f = 0; f < files.length; f++){
if(files[f].tagName == "A"){
href = S(files[f]).attr('href');
S().ajax(href,{
'this':files[f],
'dataType':'text',
'success': function(d,attr){
var s = 0;
attr.header.replace(/.*Content-Length: ([0-9]+).*/i,function(m,p1){ s = parseInt(p1); return m; });
l = d.length;
S(this).html(attr.url.replace(/resources\//,"")+' '+(l/1000).toFixed(1)+'kB'+(l!=s ? ' ('+(s/1000).toFixed(1)+'kB)':''));
},
'error': function(e,attr){
console.error('Unable to load '+attr.url);
}
});
}
}
ready(function(){
document.querySelector('.version').innerHTML = TypeAhead.version;
});
</script>
<script>
ready(function(){
// Define a function for scoring how well a string matches
function getScore(str1,str2,v1,v2,v3){
var r = 0;
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
if(str1.indexOf(str2)==0) r += (v1||3);
if(str1.indexOf(str2)>0) r += (v2||1);
if(str1==str2) r += (v3||4);
return r;
}
// Build the barchart object attached to <input type="text" id="typeahead">
var typeahead0 = TypeAhead.init('#typeahead0',{
'items': [],
'render': function(d){
// Construct the label shown in the drop down list
return d['name']+(d['IATA'] ? ' ('+d['IATA']+')':'');
},
'process': function(d){
// An airport has been selected so do something with the results
document.querySelector('#results').innerHTML = '<strong>'+d['name']+(d['IATA'] ? ' ('+d['IATA']+')':'')+(d['runway'] ? '. The runway is '+Math.round(d['runway']*(0.3)).toLocaleString()+' metres long.':'')+'</strong> <sup>[ <a href="https://en.wikipedia.org/wiki/List_of_airports_in_the_United_Kingdom_and_the_British_Crown_Dependencies">cite</a> ]</sup>';
},
'rank': function(d,str){
// Calculate the weight to add to this airport
var r = 0;
if(d['name']) r += getScore(d['name'],str);
if(d['loc']) r += getScore(d['loc'],str);
if(d['IATA']) r += getScore(d['IATA'],str,2,1);
if(d['county']) r += getScore(d['county'],str);
if(d['usage']=="Public") r += 2; // If it is a public airport we'll increase its weight
return r;
}
});
var loading = false;
// Attach a callback to the 'change' event. This gets called each time the user enters/deletes a character.
typeahead0.on('change',{'me':typeahead0},function(e){
if(!loading){
loading = true;
// We'll load the CSV, process it and add it to the item list
fetch('airports-uk.json',{}).then(response => {
if(!response.ok) throw new Error('Network response was not OK');
return response.json();
}).then(json => {
e.data.me.addItems(json);
}).catch(e => {
console.error('There has been a problem loading the data.');
});
}
});
});
</script>
<h2>CSS</h2>
<p>The type-ahead results are added in a <code><div></code> element with the class <code>typeahead-results</code>. The div contains an ordered list <code><ol></code> containing list items <code><li></code> for each result. The selected list item has the class <code>selected</code>.</p>
<h2>Examples</h2>
<h3>A simple example</h3>
<p>In this example we have a small array of six airport names that we want to search through.</p>
<div class="example-code">
<link rel="stylesheet" href="resources/typeahead.css" />
<script type="text/javascript" src="resources/typeahead.js"></script>
<script>
// Here's a function to delay execution until the document is ready.
// You could, alternatively, use jQuery's document.ready() or something similar
function ready(f){
if(/in/.test(document.readyState)) setTimeout('S(document).ready('+f+')',9);
else f();
};
ready(function(){
// Build the barchart object attached to <input type="text" id="typeahead">
typeahead1 = TypeAhead.init('#typeahead1',{
'items': [
'Leeds and Bradford Airport',
'Newcastle International Airport',
'London City Airport',
'Durham Tees Valley Airport',
'Doncaster Sheffield Airport',
'Humberside Airport'
],
'process': function(d){
// Format the result
document.querySelector('#results1').innerHTML = '<strong>'+d+'</strong>';
}
});
});
</script>
<form id="form1">
<label for="typeahead">Search for an airport:</label>
<input type="text" id="typeahead1" value="" placeholder="e.g. Leeds and Bradford" />
<div class="results">
The result is: <span id="results1"></span>
</div>
</form>
</div>
<h3>Data objects</h3>
<p>In this example we have a <code>name</code> and <code>IATA</code> code for each airport. We will rank the results with different weights depending on how we match.</p>
<div class="example-code">
<link rel="stylesheet" href="resources/typeahead.css" />
<script type="text/javascript" src="resources/typeahead.js"></script>
<script>
ready(function(){
// Build the TypeAhead object around <input type="text" id="typeahead">
var typeahead2 = TypeAhead.init('#typeahead2',{
'items': [
{'name':'Leeds and Bradford Airport','IATA':'LBA'},
{'name':'Newcastle International Airport','IATA':'NCL'},
{'name':'London City Airport','IATA':'LCY'},
{'name':'Durham Tees Valley Airport','IATA':'MME'},
{'name':'Doncaster Sheffield Airport','IATA':'DSA'},
{'name':'Humberside Airport','IATA':'HUY'}
],
'rank': function(d,str){
// Calculate a weighting
var r = 0;
// If the name starts with the string add 3
if(d.name.toUpperCase().indexOf(str.toUpperCase())==0) r += 3;
// If the name includes the string add 1
if(d.name.toUpperCase().indexOf(str.toUpperCase())>0) r += 1;
// If the IATA code starts with the string add 3
if(d.IATA.toUpperCase().indexOf(str.toUpperCase())==0) r += 3;
// If the IATA code matches
if(d.IATA.toUpperCase() == str.toUpperCase()) r += 3;
return r;
},
'render': function(d){
// Render the drop down list item for each airport.
// This can be HTML. It will be wrapped in <a>
return d.name;
},
'process': function(d){
// An airport has been selected so show the result
document.querySelector('#results2').innerHTML = '<strong>'+d.name+' ('+d.IATA+')</strong>';
}
});
});
</script>
<form id="form2">
<label for="typeahead2">Search for an airport:</label>
<input type="text" id="typeahead2" value="" placeholder="e.g. Leeds" />
<div class="results">
The result is: <span id="results2"></span>
</div>
</form>
</div>
<h3>Load results from a separate file</h3>
<p>Sometimes you may want to reduce initial page load or just have the searchable values in a separate file. This example loads results from a JSON file on the first key press. If the file is large, this can lead to a delay before the type-ahead results show up. It uses a custom function to define how the input text matches with each item; it matches on <code>name</code>, <code>IATA</code>, <code>county</code> and <code>loc</code> giving a higher weight if a field starts with the string than if it contains the string.</p>
<div class="example-code">
<link rel="stylesheet" href="resources/typeahead.css" />
<script type="text/javascript" src="resources/typeahead.js"></script>
<script>
ready(function(){
// Define a function for scoring how well a string matches
function getScore(str1,str2,v1,v2,v3){
var r = 0;
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
if(str1.indexOf(str2)==0) r += (v1||3);
if(str1.indexOf(str2)>0) r += (v2||1);
if(str1==str2) r += (v3||4);
return r;
}
// Build the TypeAhead object around <input type="text" id="typeahead">
var typeahead3 = TypeAhead.init('#typeahead3',{
'items': [],
'max': 8, // Set a maximum number to list
'render': function(d){
// Construct the label shown in the drop down list
return d['name']+(d['IATA'] ? ' ('+d['IATA']+')':'');
},
'process': function(d){
// An airport has been selected so do something with the results
document.querySelector('#results3').innerHTML = '<strong>'+d['name']+(d['IATA'] ? ' / '+d['IATA']:'')+(d['runway'] ? ' / '+d['runway'].toLocaleString()+' ft':'')+'</strong>';
},
'rank': function(d,str){
// Calculate the weight to add to this airport
var r = 0;
if(d['name']) r += getScore(d['name'],str);
if(d['loc']) r += getScore(d['loc'],str);
if(d['IATA']) r += getScore(d['IATA'],str,2,1);
if(d['county']) r += getScore(d['county'],str);
if(d['usage']=="Public") r += 2; // If it is a public airport we'll increase its weight
return r;
}
});
var loading = false;
// Attach a callback to the 'change' event. This gets called each time the user enters/deletes a character.
typeahead3.on('change',{'me':typeahead3},function(e){
if(!loading){
loading = true;
// We'll load the CSV, process it and add it to the item list
fetch('airports-uk.json',{}).then(response => {
if(!response.ok) throw new Error('Network response was not OK');
return response.json();
}).then(json => {
e.data.me.addItems(json);
e.data.me.trigger('change',e);
}).catch(e => {
console.error('There has been a problem loading route data.');
});
}
});
});
</script>
<form id="form3">
<label for="typeahead3">Search for a UK airport:</label><br />
<input type="text" id="typeahead3" value="" placeholder="e.g. Leeds" />
<div class="results">
The result is: <span id="results3"></span>
</div>
</form>
</div>
<h3>Load results from a separate CSV file</h3>
<p>Sometimes you may want to reduce initial page load or just have the searchable values in a separate file. This example loads results on the first key press. If the file is large, this can lead to a delay before the type-ahead results show up.</p>
<div class="example-code">
<link rel="stylesheet" href="resources/typeahead.css" />
<script type="text/javascript" src="resources/typeahead.js"></script>
<script>
ready(function(){
// Build the TypeAhead object around <input type="text" id="typeahead">
var typeahead4 = TypeAhead.init('#typeahead4',{
'items': [],
'max': 8, // Set a maximum number to list
'render': function(d){
// Construct the label shown in the drop down list
return d['Airport name']+(d['IATA'] ? ' ('+d['IATA']+')':'');
},
'process': function(d){
// An airport has been selected so do something with the results
document.querySelector('#results4').innerHTML = '<strong>'+d['Airport name']+(d['IATA'] ? ' / '+d['IATA']:'')+(d['Rwy (ft)'] ? ' / '+parseInt(d['Rwy (ft)']).toLocaleString()+' ft':'')+'</strong>';
},
'rank': function(d,str){
// Calculate the weight to add to this airport
var r = 0;
if(d['Airport name']){
// The airport name starts with the string
if(d['Airport name'].toUpperCase().indexOf(str.toUpperCase())==0) r += 3;
// The airport name contains the string
if(d['Airport name'].toUpperCase().indexOf(str.toUpperCase())>0) r += 1;
}
// The location starts with the string
if(d['Location'] && d['Location'].toUpperCase().indexOf(str.toUpperCase())==0) r += 3;
// If it has an IATA code we increase the weighting as it is a larger airport
if(d['IATA']){
r += 1;
if(d['IATA'].toUpperCase().indexOf(str.toUpperCase())==0) r += 2;
if(d['IATA'].toUpperCase() == str.toUpperCase()) r += 2;
}
// If it is a public airport we'll increase its weight
if(d['Usage']=="Public") r += 2;
return r;
}
});
var loading = false;
// Attach a callback to the 'change' event. This gets called each time the user enters/deletes a character.
typeahead4.on('change',{'me':typeahead4},function(e){
if(!loading){
loading = true;
// We'll load the CSV, process it and add it to the item list
fetch('airports-uk.csv',{}).then(response => {
if(!response.ok) throw new Error('Network response was not OK');
return response.text();
}).then(d => {
d = d.split(/[\n]/);
var l,cols,header,datum,c;
var data = new Array(d.length-1);
for(l = 0; l < d.length; l++){
cols = d[l].split(/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/);
if(l == 0) header = cols;
else{
datum = {};
for(c = 0; c < cols.length; c++) datum[header[c]] = cols[c].replace(/(^\"|\"$)/g,"");
data[l-1] = datum;
}
}
e.data.me.addItems(data);
e.data.me.trigger('change',e);
}).catch(e => {
console.error('There has been a problem loading route data.');
});
}
});
});
</script>
<form id="form4">
<label for="typeahead4">Search for a UK airport:</label><br />
<input type="text" id="typeahead4" value="" placeholder="e.g. Leeds" />
<div class="results">
The result is: <span id="results4"></span>
</div>
</form>
</div>
</div>
<script language="javascript" type="text/javascript" src="resources/formatexamples.js"></script>
</body>
</html>