-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcsv2table.js
476 lines (424 loc) · 10.8 KB
/
csv2table.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
/**
* Simple example of creating a web interactive table from CSV data.
*
* The goal is showing a simple example of using open libraries to vizualize
* CSV data in a browser.
* Along with sorting, filtering and exporting capabilities.
*
* Ppen source libraries :
* - Bootstrap (https://getbootstrap.com/)
* - JQuery (https://jquery.com/)
* - bootstrap-table (https://bootstrap-table.com/docs/getting-started/usage/)
* - boostratp-table-export
* - JQuery-CSV (https://github.com/typeiii/jquery-csv)
*
* @link https://github.com/EL-BID/IDB-Lab-Map-LAC-Innovators-Coronavirus
*
* @author Julien Collaer @IDB Lab
*
* @datte 2020
*/
/** jshint {} */
var countries = [];
var categories = [];
var sources = [];
var showDetails = false;
/**
* Extending String for a truncate capability
*/
String.prototype.trunc = String.prototype.trunc ||
function(n){
return (this.length > n) ? this.substr(0, n-1) + '…' : this;
};
/**
*
* Function receiving CSV response data object Must be CSV
* Will parse CSV into a list of objects
* Creating table structure.
* Creating combox filtering options for 3 columns:
* - category
* - country
* - source
* Initializing filtering event on combobox
* Setting show detail event for switching showing full description text or not
*
* @since 2020
*
* @param {data} html response MUST BE CSV content
*/
var processData = function(data) {
csv = $.csv.toObjects(data);
$('#datatable').bootstrapTable({
pagination: true,
search: true,
pagination: true,
toolbar: "#toolbar-table",
showExport: true,
exportDataType: "all",
showColumns: true,
showFullscreen: true,
showFooter: true,
detailView: true,
detailViewByClick: true,
detailViewIcon: true,
detailFormatter: detailDescriptionFormatter,
columns: [{
field: 'organization',
title: 'Organization',
width: '20',
widthUnit: '%',
sortable: true,
formatter: linkAccount,
footerFormatter: TotalFormatter,
detailFormatter: detailDescriptionFormatter
}, {
field: 'category',
title: 'Category',
width: '20',
widthUnit: '%',
sortable: true,
footerFormatter: CategoriesFormatter,
detailFormatter: detailDescriptionFormatter
}, {
field: 'country',
title: 'Country',
width: '10',
widthUnit: '%',
sortable: true,
footerFormatter: CountriesFormatter,
detailFormatter: detailDescriptionFormatter
}, {
field: 'description',
title: 'Description',
width: '40',
widthUnit: '%',
sortable: false,
formatter: descriptionFormatter,
detailFormatter: detailDescriptionFormatter
}, {
field: 'url2',
title: 'Additional link',
width: '10',
widthUnit: '%',
formatter: LinkFormatter,
detailFormatter: detailDescriptionFormatter
}, {
field: 'url',
title: 'url',
width: '0.1',
widthUnit: '%',
visible: false
}],
data: csv
});
countries = [];
categories = [];
sources = [""];
$.each(csv, function(i,d) {
if(! countries.includes(d.country)) {
countries.push(d.country);
$("#country")
.append('<option val="' + d.country + '">'+ d.country + '</option>');
}
if(! categories.includes(d.category)) {
categories.push(d.category);
$("#category")
.append('<option val="' + d.category + '">'+ d.category + '</option>');
}
if(! sources.includes(d.source)) {
sources.push(d.source);
$("#source")
.append('<option val="' + d.source + '">'+ d.source + '</option>');
}
});
$("#country").selectpicker('refresh');
$("#category").selectpicker('refresh');
$("#source").selectpicker('refresh');
$("#country" ).change(function() {
refreshFilter();
});
$( "#category" ).change(function() {
refreshFilter();
});
$( "#source" ).change(function() {
refreshFilter();
});
$( "#more_detail").on("click", function() {
showDetails = showDetails == false;
refreshFilter();
});
};
/**
*
* Function refreshing filters to datatable from combobox current values
*
* @since 2020
*
*/
var refreshFilter = function() {
var country = $("#country").val();
var category = $("#category").val();
var source = $("#source").val();
filters = {};
if (country != 0) {
filters["country"] = country;
};
if (category != 0) {
filters["category"] = category;
};
if (source != 0) {
filters["source"] = source;
};
$('#datatable').bootstrapTable('filterBy', filters);
};
/**
* link account formatter to se url link form URL field value (missing http prefix)
*
* @since 2020
*
* @param {value} field value being evaluated
* @param {row} current row object being evaluated
* @param {index} integer index of current row being evaluated
*/
var linkAccount = function (value, row, index) {
return [
'<a href="http://',
row.url,
'" title="Open webpage of ',
row.organization,
' in antoher window." target="_blank">',
value,
'</a>'].join('');
};
/**
* link formatter to se url link form same field value
* value must be an URL without HTTPS prefix
*
* @since 2020
*
* @param {value} field value being evaluated
* @param {row} current row object being evaluated
* @param {index} integer index of current row being evaluated
*/
var LinkFormatter = function(value, row, index) {
return [
'<a href="http://',
value,
'" title="Open ',
value,
' in antoher window." target="_blank">',
value,
'</a>'].join('');
}
/**
* Total Formater for being use at the bottom of the table
* bootstrap table total formatter option
* Will return a string contactenating the length of rows
*
* @since 2020
*
* @param {data} the whole table data with current filters applied
*/
var TotalFormatter = function(data) {
return 'Total: ' + data.length;
};
/**
* Total formatter to get number of differents countries in the data
*
* @since 2020
*
* @param {data} the whole table data with current filters applied
*/
var CountriesFormatter = function(data) {
var currentData = $("#datatable").bootstrapTable('getData');
var countries_f = [];
$.each(currentData, function(i,d) {
if(! countries_f.includes(d.country)) {
countries_f.push(d.country);
}
});
return countries_f.length + ' countries';
};
/**
* Total formatter to get the 3 most frequent categories along the number
* of occurence next to each ones.
*
* @since 2020
*
* @param {data} the whole table data with current filters applied
*/
var CategoriesFormatter = function(data) {
var currentData = $("#datatable").bootstrapTable('getData');
var categories_f = [];
$.each(currentData, function(i,d) {
if(! categories_f.includes(d.category)) {
categories_f.push(d.category);
}
});
var cata = {};
$.each(currentData, function(i, record) {
cata[record.category] = (cata[record.category] ? cata[record.category] + 1 : 1);
});
var text = categories_f.length + ' categories.';
//https://stackoverflow.com/questions/1069666/sorting-object-property-by-values
var keysSorted = Object.keys(cata).sort(function(a,b){return cata[b]-cata[a]});
i=0
$.each(keysSorted, function(position, key) {
if (i > 2) {
return;
}
text += "<br />" + key.toString().trunc(18) + ": " + cata[key];
i++;
});
return text;
};
/**
* Description field table formatter to truncate of not the content using a global parameter.
*
* @since 2020
*
* @param {value} field value being evaluated
* @param {row} current row object being evaluated
* @param {index} integer index of current row being evaluated
*/
var descriptionFormatter = function (value, row, index) {
if (showDetails)
return value;
else
return value.trunc(133);
};
/**
* Detail formatter for description to replace new lines and return cariage to
* actual lines jumps using html break tags
*
* @since 2020
*
* @param {value} field value being evaluated
* @param {row} current row object being evaluated
* @param {index} integer index of current row being evaluated
*/
var detailDescriptionFormatter = function (value, row, index) {
return row.description.replace(/(\r\n|\n|\r)/gm,"<br />");
};
/**
*
* When document is ready.
* AJAX request to get CSV data from URL and calling the processData function upon receiving it.
* @todo managing errors, etc.
*
* @since 2020
*/
$(document).ready(function() {
$.ajax({
type: "GET",
url: "https://idb-gis.maps.arcgis.com/sharing/rest/content/items/70434cfbfcd5440486ab5e870302184c/data",
dataType: "text",
success: function(data) {
processData(data);
initCharts($('#datatable'));
refreshFilter();
}
});
});
/**
*
* chartjs initialization binfing it to a datatable
*
*
* @since 2020
*/
var initCharts = function(datatable) {
eventName = 'post-body.bs.table';
datatable.on(eventName, function (e, data) {
refreshGraphs();
});
};
/**
*
* Funtion that retrieve subtotals for fields occurence into a data fron a datatable
*
* @return a configuration object for labels and data ready to be use by chartjs
*
* @todo ordering by count desc
*
* @since 2020
*/
var getTotalsForAttribute = function(currentData, field) {
var structure = {
labels:[],
datas:[{data:[]}]
};
$.each(currentData, function(i,d) {
var fieldValue = d[field];
//console.log(fieldValue);
var a = structure.labels.indexOf(fieldValue);
if(a == -1) {
structure.labels.push(fieldValue)
structure.datas[0].data.push(1);
} else {
structure.datas[0].data[a] ++;
}
});
return structure;
};
/**
*
* Refresh charts js graph function
*
* Will recompute the data if is this filtered and redraw/destroy graph
*
* @todo make it clean by not using global vars but implementing a class singleton object
*
* @since 2020
*/
var chartCategories;
var chartCountries;
var refreshGraphs = function() {
var currentData = $('#datatable').bootstrapTable("getData");
var countries = getTotalsForAttribute(currentData, "country");
var categories = getTotalsForAttribute(currentData, "category");
if (chartCountries)
chartCountries.destroy();
if (chartCategories)
chartCategories.destroy();
chartCountries = new Chart("chartCanvas1", {
type: 'bar',
data: {
labels: countries.labels,
datasets: countries.datas
},
options: {
plugins: {
colorschemes: {
scheme: 'brewer.Paired12'
}
},
animation: {
duration: 1000,
},
legend: {
display: false,
},
}
});
chartCategories = new Chart("chartCanvas2", {
type: 'bar',
data: {
labels: categories.labels,
datasets: categories.datas
},
options: {
plugins: {
colorschemes: {
scheme: 'brewer.Paired12'
}
},
animation: {
duration: 1000,
},
legend: {
display: false,
},
}
});
};