-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.html
392 lines (358 loc) · 14.3 KB
/
table.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
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Render csv/tsv files (provided either locally or using html arguments) into HTML DataTable using jquery and bootstrap." />
<title>CSV to DataTable</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14;
padding-left: 5%;
padding-right: 5%;
}
#tableTitle {
color: gray;
padding-top: 50px;
font-size: x-large;
}
#tableContainer {display: none}
#loaderContainer{
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
th {
text-align: left;
}
.btn {
text-decoration: none;
color: royalblue;
background-color: rgb(188, 205, 255);
padding: 10px 20px 10px 20px;
border-radius: 8px;
}
.btn:hover {
color: rgb(188, 205, 255);
background-color: royalblue;
font-weight: bold;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.282);
cursor: pointer;
}
</style>
</head>
<body>
<div id="navbar">
<p><a class='btn' href='javascript:history.back()'>Go Back</a></p>
</div>
<h1 id="tableTitle"></h1>
<div id="usage_guide">
<p>This is a general purpose tool to render tabular data into resposnive, searchable, and sortable html datatables.</p>
<p><strong>Github Repository: </strong><a href="https://github.com/Ghahfarokhi/htmltools-csv-to-datatable">htmltools-csv-to-datatable</a></p>
<p><strong>Usage guideline</strong></p>
<p>This file contains all html, css, and javascript codes needed to read a set of url parameters listed below
and display the datatable which has been pointed to. Simply let this file to live in the root of your
project folder on any server. All the codes will execute on the client-side.
</p>
<p><strong>URL construction</strong></p>
<p style="color: gray;">
<b>Example:</b>
https://.../table.html<b style="color: red;">?</b>table_name=data/tab_separated_table.tsv<b style="color: red;">&</b>table_title=myTable<b style="color: red;">&</b>style=compact,stripe
<br>
<br>
<b>Demo:</b> <a href="https://amirtaheri.info/htmltools-csv-to-datatable/table.html?table_name=data/tab_separated_table.tsv&table_title=CSV%20to%20Datatable%20Demo">Visit this link for a working example!</a>
</p>
<p><strong>Parameters</strong></p>
<ul>
<li><b>table_name</b>: required!</li>
<li><b>table_title</b>: optional (values: a cutom title), default=table_name.</li>
<li><b>separator</b>: optional (values: , or ; or : ), default=tab.</li>
<li><b>paging</b>: optional (values: true or false), default=true</li>
<li><b>column_filtering</b>: optional (values: true or false), default=false.</li>
<li><b>scroll_x</b>: optional (values: true or false), default=true</li>
<li><b>style</b>: optional (values: none, display, compact, stripe, hover, cell-border, row-border,
order-column), default=display,compact.
Multiple value combinations can be used together, separated using a comma.</li>
</ul>
<hr>
<p><strong>Note 1</strong>: Parameters and their values should follow the pattern shown in the example above
(e.g.,&parameterX=valueX&parameterY=valueY and so on). Order of parameters doesn't matter.
</p>
<p><strong>Note 2</strong>: If you still see this guideline after providing the url paramaters,
then double check the spelling of "<b style="color: royalblue;">table_name</b>".
</p>
<p><strong>Note 3</strong>: Table text will be sanitized before its addition to the DOM, meaning any charachter outside
of the following white-list will be removed before appending the cell text to the datatable.
The white-list is limited to: <b>A-Z0-9a-z./-_() ,;:*+=!?@'"#€$%&</b>. Developers: consult the <i>generalStringSanitizer</i> function if a
more relaxed sanitizer is needed.
</p>
<br>
<hr>
<p><strong>References and dependencies</strong></p>
<ul>
<li>CSVToArray Function: <a href="https://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm">Ben Nadal's blog</a></li>
<li>Datatables: <a href="https://datatables.net/">datatables.net</a></li>
<li>Javascript library: <a href="https://jquery.com/">jQuery</a></li>
<li>Assembly: <a href="https://amirtaheri.info">Amir Taheri Ghahfarokhi</a></li>
</ul>
</div>
<hr>
<div id="tableContainer" class="m-5"></div>
<div id="loaderContainer">
<div class="d-flex justify-content-center text-secondary" id="loader">
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
</div>
<div id="footer">
<p style="color: gray; text-align: center; padding: 50px;">CSVtoDatatable</p>
</div>
<!-- Scripts are placed here to help with the page loading faster -->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
/***********************
Script sections:
0- Helper functions
1- Read URL Arguments
2- CSVtoArray function
3- ArraytoHTML Function
************************/
/************************
0- Helper Functions
************************/
function pad(num, size) {
var s = "00000000" + num;
return s.substr(s.length-size);
}
function generalStringSanitizer(anyText) {
var anyText = String(anyText);
anyText = anyText.replace(/[^A-Z0-9a-z_.\/-_() ,;:*+=!?@"'#€$%&]/gi,' ');
return (anyText);
}
function generateArray(numRow, numCol){
var myArray = new Array(numRow);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = new Array(numCol);
}
for (var j = 0; j < numCol;j++) {
myArray[0][j] = 'Col_' + pad(j+1, 2);
}
for (i = 1; i < numRow; i++) {
for (j = 0; j < numCol; j++) {
myArray[i][j] = 'R_' + pad(i, 2) + ' , C_' + pad(j+1, 2);
}
}
return myArray;
}
/************************
1- Read URL Argument(s)
************************/
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var table_name = urlParams.get('table_name') || false;
var table_title = urlParams.get('table_title') || table_name;
var separator = urlParams.get('separator') || '\t';
var column_filtering = urlParams.get('column_filtering') || false;
var style = urlParams.get('style') || 'display,compact';
var paging = urlParams.get('paging') || true;
var scroll_x = urlParams.get('scroll_x') || true;
/* Sanitize url parameters */
if (table_name !== false) {
table_name = table_name.replace(/[^A-Z0-9a-z()_.\/-]/gi,'');
table_name = table_name.replace('//','/');
table_title = table_title.replace(/[^A-Z0-9a-z() _.\/-]/gi,'');
}
separator = separator.replace(/[^:;,]/gi,'');
style = style.replace(/[^A-Za-z,-]/gi,'');
/* Validate url parameters */
if (table_name === false) {
/* Show some hints */
var table_title = 'ATG DataTable Tool v0.1';
$("#usage_guide").css("display","block");
$("#loaderContainer").css("display","none");
} else {
/* check if table_name exists */
var table_file = new XMLHttpRequest();
table_file.open('HEAD', table_name, false);
table_file.send();
if (table_file.status != 200) {
table_title = "Errrrr! Couldn't find: " + table_name;
$("#loaderContainer").css("display","none");
$("#usage_guide").css("display","block");
$("#usage_guide").text('Please double-check the spelling of the value for table_name!');
} else {
$("#usage_guide").css("display","none");
}
}
if (column_filtering === '1' || column_filtering === 'true') {
var column_filtering = true;
} else {
var column_filtering = false;
}
if (paging === '0' || paging === 'false') {
var paging = false;
} else {
var paging = true;
}
if (scroll_x === '0' || scroll_x === 'false') {
var scroll_x = false;
} else {
var scroll_x = true;
}
style = style.replace(',' , ' ');
style = style.replace('none' , ' ');
/************************
2- CSV to Array
************************/
function CSVToArray(strData, strDelimiter){
// CSVToArray Source: https://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
// Check to see if the delimiter is defined. If not,
// then default to tab.
strDelimiter = (strDelimiter || "\t");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}
/************************
3- Array to HTML
************************/
function drawDataTable() {
$("#tableTitle").text(table_title);
var $table = $('<table id="example" class="nowrap" style="width:100%">');
var $tableContainer = $("#tableContainer");
$tableContainer.empty().append($table);
var $tableHtmlHead = $("<thead></thead>");
var tableDataHeaderRow = tableData[0];
var $tableHtmlHeadRow = $("<tr></tr>");
for (var headerIdx = 0; headerIdx < tableDataHeaderRow.length; headerIdx++) {
$tableHtmlHeadRow.append($("<th></th>").text(generalStringSanitizer(tableDataHeaderRow[headerIdx])));
}
$tableHtmlHead.append($tableHtmlHeadRow);
$table.append($tableHtmlHead);
var $tableHtmlBody = $("<tbody></tbody>");
var numColumns = tableDataHeaderRow.length;
for (var rowIdx = 1; rowIdx < tableData.length; rowIdx++) {
var $tableHtmlBodyRow = $("<tr></tr>");
if (tableData[rowIdx].length === numColumns) {
for (var colIdx = 0; colIdx < tableData[rowIdx].length; colIdx++) {
var $tableHtmlBodyRowTd = $("<td></td>");
$tableHtmlBodyRowTd.text(generalStringSanitizer(tableData[rowIdx][colIdx]));
$tableHtmlBodyRow.append($tableHtmlBodyRowTd);
$tableHtmlBody.append($tableHtmlBodyRow);
}
}
}
if (style !== 'none') {
$("#example").addClass(style);
}
$table.append($tableHtmlBody);
$tableContainer.append("<p><a class='btn' href='" + table_name + "'>Download Table</a></p>");
if (column_filtering === true) {
$('#example thead tr').clone(true).appendTo( '#example thead' );
$('#example thead tr:eq(1) th').each( function (i) {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
$( 'input', this ).on( 'keyup change', function () {
if ( table.column(i).search() !== this.value ) {
table
.column(i)
.search( this.value )
.draw();
}
});
});
$table.on('draw.dt', function () {
$("#tableContainer").attr("id", "container");
$("#loaderContainer").css("display","none");
}
);
var table = $('#example').DataTable( {
"lengthChange": true,
"scrollX": scroll_x,
"orderCellsTop": true,
"paging": paging
}).columns.adjust();
} else {
$table.on('draw.dt', function () {
$("#tableContainer").attr("id", "container");
$("#loaderContainer").css("display","none");}).DataTable({
"lengthChange": true,
"scrollX": scroll_x,
"paging": paging
}
).columns.adjust(); // End table.on
} // End if else
} // End Function drawDataTable
if (table_name === false) {
/* Let's make a dummy array */
tableData = generateArray(53, 5);
drawDataTable();
} else {
$.get(table_name).then(
function (data) {
tableData = CSVToArray(data, separator);
drawDataTable();
}
);
}
</script>
</body>
</html>