Debian Codegraph @

js/widgets/widget-build-table.js

raw symbols SCIP
1 /*! Widget: Build Table - updated 2018-03-26 (v2.30.2) *//*
2 * for tableSorter v2.16.0+
3 * by Rob Garrison
4 */
5 /*jshint browser:true, jquery:true, unused:false */
6 /*global jQuery: false */
7 ;(function($) {
8 'use strict';
9 var ts = $.tablesorter = $.tablesorter || {},
10
11 // build a table from data (requires existing <table> tag)
12 // data.header contains an array of header titles
13 // data.rows contains an array of rows which contains an array of cells
14 bt = ts.buildTable = function(tar, c) {
15 // add build options to defaults to prevent warnings
16 $.extend(true, ts.defaults.widgetOptions, bt.defaults);
17 // add table if one doesn't exist
18 var $tbl = tar.nodeName === 'TABLE' ? $(tar) : $('<table>').appendTo(tar),
19 table = $tbl[0],
20 wo = c.widgetOptions = $.extend( true, {}, bt.defaults, c.widgetOptions ),
21 p = wo.build_processing,
22 typ = wo.build_type,
23 d = wo.build_source || c.data,
24 debug = ts.debug(c, 'build'),
25
26 // determine type: html, json, array, csv, object
27 runType = function(d) {
28 var t = $.type(d),
29 jq = d instanceof $;
30 // run any processing if set
31 if ( typeof p === 'function' ) { d = p(d, wo); }
32 // store processed data in table.config.data
33 c.data = d;
34 // String (html or unprocessed json) or jQuery object
35 if ( jq || t === 'string' ) {
36 // look for </tr> closing tag, then we have an HTML string
37 if ( jq || /<\s*\/tr\s*>/.test(d) ) {
38 return bt.html( table, d, wo );
39 }
40 try {
41 d = $.parseJSON(d || 'null');
42 if (d) {
43 // valid JSON!
44 return bt.object( table, d, wo );
45 }
46 } catch (ignore) {}
47 // fall through in case it's a csv string
48 }
49 // Array
50 if (t === 'array' || t === 'string' || typ === 'array' || typ === 'csv') {
51 // build table using an array (csv & array combined script)
52 return bt.csv( table, d, wo );
53 }
54 // if we got here, it's an object, or nothing
55 return bt.object( table, d, wo );
56 };
57
58 // store config
59 table.config = c;
60
61 // even if wo.build_type is undefined, we can try to figure out the type
62 if ( !ts.buildTable.hasOwnProperty(typ) && typ !== '' ) {
63 if (debug) {
64 console.error('Build >> ERROR: Aborting build table widget, incorrect build type');
65 }
66 return false;
67 }
68
69 if ( d instanceof $ ) {
70 // get data from within a jQuery object (csv)
71 runType( $.trim( d.html() ) );
72 } else if ( d && ( d.hasOwnProperty('url') || typ === 'json' ) ) {
73 // load data via ajax
74 $.ajax( wo.build_source )
75 .done(function(data) {
76 runType(data);
77 })
78 .fail(function( jqXHR, textStatus) {
79 if (debug) {
80 console.error('Build >> ERROR: Aborting build table widget, failed ajax load');
81 }
82 $tbl.html('<tr><td class="error">' + jqXHR.status + ' ' + textStatus + '</td></tr>');
83 });
84 } else {
85 runType(d);
86 }
87 };
88
89 // add data to defaults for validator; value must be falsy!
90 ts.defaults.data = '';
91
92 bt.defaults = {
93 // *** build widget core ***
94 build_type : '', // array, csv, object, json, html
95 build_source : '', // array, object, jQuery Object or ajaxObject { url: '', dataType: 'json' },
96 build_processing : null, // function that returns a useable build_type (e.g. string to array)
97 build_complete : 'tablesorter-build-complete', // triggered event when build completes
98
99 // *** CSV & Array ***
100 build_headers : {
101 rows : 1, // Number of header rows from the csv
102 classes : [], // Header classes to apply to cells
103 text : [], // Header cell text
104 widths : [] // set header cell widths (set in colgroup)
105 },
106 build_footers : {
107 rows : 1, // Number of header rows from the csv
108 classes : [], // Footer classes to apply to cells
109 text : [] // Footer cell text
110 },
111 build_numbers : {
112 addColumn : false, // include row numbering column?
113 sortable : false // make column sortable?
114 },
115
116 // *** CSV only options ***
117 build_csvStartLine : 0, // line within the csv to start adding to table
118 build_csvSeparator : ',', // csv separator
119
120 // *** build object options ***
121 build_objectRowKey : 'rows', // object key containing table rows
122 build_objectCellKey : 'cells', // object key containing table cells (within the rows object)
123 build_objectHeaderKey : 'headers', // object key containing table headers
124 build_objectFooterKey : 'footers' // object key containing table footers
125 };
126
127 bt.build = {
128 colgroup : function(widths) {
129 var t = '';
130 // add colgroup if widths set
131 if (widths && widths.length) {
132 t += '<colgroup>';
133 $.each(widths, function(i, w) {
134 t += '<col' + ( w ? ' style="width:' + w + '"' : '' ) + '>';
135 });
136 t += '</colgroup>';
137 }
138 return t;
139 },
140 // d = cell data; typ = 'th' or 'td'; first = save widths from first header row only
141 cell : function(d, wo, typ, col, first) {
142 var j, $td,
143 $col = first ? $('<col>') : '',
144 cls = wo.build_headers.classes,
145 cw = wo.build_headers.widths;
146 // d is just an array
147 if (/string|number/.test(typeof d)) {
148 // add classes from options, but not text
149 $td = $('<' + typ + (cls && cls[col] ? ' class="' + cls[col] + '"' : '') + '>' + d + '</' + typ + '>');
150 // get widths from options (only from first row)
151 if (first && cw && cw[col]) {
152 $col.width(cw[col] || '');
153 }
154 } else {
155 // assume we have an object
156 $td = $('<' + typ + '>');
157 for (j in d) {
158 if (d.hasOwnProperty(j)) {
159 if (j === 'text' || j === 'html') {
160 $td[j]( d[j] );
161 } else if (first && j === 'width') {
162 // set column width, but only from first row
163 $col.width(d[j] || '');
164 } else {
165 $td.attr(j, d[j]);
166 }
167 }
168 }
169 }
170 return [ $td, $col ];
171 },
172 // h1 = header text from data
173 header : function(h1, wo) {
174 var h2 = wo.build_headers.text,
175 cls = wo.build_headers.classes,
176 t = '<tr>' + (wo.build_numbers.addColumn ? '<th' + (wo.build_numbers.sortable ? '' :
177 ' class="sorter-false"') + '>' + wo.build_numbers.addColumn + '</th>' : '');
178 $.each(h1, function(i, h) {
179 if (/<\s*\/t(d|h)\s*>/.test(h)) {
180 t += h;
181 } else {
182 t += '<th' + (cls && cls[i] ? ' class="' + cls[i] + '"' : '') + '>' +
183 (h2 && h2[i] ? h2[i] : h) + '</th>';
184 }
185 });
186 return t + '</tr>';
187 },
188 rows : function(items, txt, c, wo, num, ftr) {
189 var h = (ftr ? 'th' : 'td'),
190 t = '<tr>' + (wo.build_numbers.addColumn ? '<' + h + '>' + (ftr ? '' : num) + '</' + h + '>' : '');
191 $.each(items, function(i, item) {
192 // test if HTML is already included; look for closing </td>
193 if (/<\s*\/t(d|h)\s*>/.test(item)) {
194 t += item;
195 } else {
196 t += '<' + (ftr ? h + (c && c[i] ? ' class="' + c[i] + '"' : '') : h) + '>' +
197 (ftr && txt && txt.length && txt[i] ? txt[i] : item) + '</' + h + '>';
198 }
199 });
200 return t + '</tr>';
201 }
202 };
203
204 bt.buildComplete = function(table, wo) {
205 $(table).triggerHandler(wo.build_complete);
206 if (table.config && ts.debug(table.config, 'build')) {
207 console.log('Build >> Table build complete');
208 }
209 ts.setup(table, table.config);
210 };
211
212 /* ==== Array example ====
213 [
214 [ "header1", "header2", ... "headerN" ],
215 [ "row1cell1", "row1cell2", ... "row1cellN" ],
216 [ "row2cell1", "row2cell2", ... "row2cellN" ],
217 ...
218 [ "rowNcell1", "rowNcell2", ... "rowNcellN" ]
219 ]
220 */
221 bt.array = function(table, data, wo) {
222 return bt.csv(table, data, wo);
223 };
224
225 /* ==== CSV example ====
226 ID, Name, Age, Date
227 A42b, Parker, 28, "Jul 6, 2006 8:14 AM"
228 A255, Hood, 33, "Dec 10, 2002 5:14 AM"
229 A33, Kent, 18, "Jan 12, 2003 11:14 AM"
230 A1, Franklin, 45, "Jan 18, 2001 9:12 AM"
231 A102, Evans, 22, "Jan 18, 2007 9:12 AM"
232 A42a, Everet, 22, "Jan 18, 2007 9:12 AM"
233 ID, Name, Age, Date
234 */
235 // Adapted & modified from csvToTable.js by Steve Sobel
236 // MIT license: https://code.google.com/p/jquerycsvtotable/
237 bt.csv = function(table, data, wo) {
238 var c, h,
239 csv = wo.build_type === 'csv' || typeof data === 'string',
240 $t = $(table),
241 lines = csv ? data.replace('\r', '').split('\n') : data,
242 len = lines.length,
243 printedLines = 0,
244 infooter = false,
245 r = wo.build_headers.rows + (csv ? wo.build_csvStartLine : 0),
246 f = wo.build_footers.rows,
247 headerCount = 0,
248 error = '',
249 items,
250 tableHTML = bt.build.colgroup( wo.build_headers.widths ) + '<thead>';
251
252 $.each(lines, function(n, line) {
253 if ( n >= len - f ) { infooter = true; }
254 // build header
255 if ( (csv ? n >= wo.build_csvStartLine : true) && ( n < r ) ) {
256 h = csv ? bt.splitCSV( line, wo.build_csvSeparator ) : line;
257 headerCount = h.length;
258 tableHTML += bt.build.header(h, wo);
259 } else if ( n >= r ) {
260 // build tbody & tfoot rows
261 if (n === r) {
262 tableHTML += '</thead><tbody>';
263 }
264 items = csv ? bt.splitCSV( line, wo.build_csvSeparator ) : line;
265 if (infooter && f > 0) {
266 tableHTML += (n === len - f ? '</tbody><tfoot>' : '') +
267 (n === len ? '</tfoot>' : '');
268 }
269 if (items.length > 1) {
270 printedLines++;
271 if ( items.length !== headerCount ) {
272 error += 'error on line ' + n + ': Item count (' + items.length +
273 ') does not match header count (' + headerCount + ') \n';
274 }
275 c = infooter ? wo.build_footers.classes : '';
276 tableHTML += bt.build.rows(items, wo.build_footers.text, c, wo, printedLines, infooter);
277 }
278 }
279 });
280 tableHTML += (f > 0 ? '' : '</tbody>');
281 if (error) {
282 $t.html(error);
283 } else {
284 $t.html(tableHTML);
285 bt.buildComplete(table, wo);
286 }
287 };
288
289 // CSV Parser by Brian Huisman (http://www.greywyvern.com/?post=258)
290 bt.splitCSV = function(str, sep) {
291 var x, tl,
292 thisCSV = $.trim(str).split(sep = sep || ',');
293 for ( x = thisCSV.length - 1; x >= 0; x-- ) {
294 if ( thisCSV[x].replace(/\"\s+$/, '"').charAt(thisCSV[x].length - 1) === '"' ) {
295 if ( (tl = thisCSV[x].replace(/^\s+\"/, '"')).length > 1 && tl.charAt(0) === '"' ) {
296 thisCSV[x] = thisCSV[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
297 } else if (x) {
298 thisCSV.splice(x - 1, 2, [ thisCSV[x - 1], thisCSV[x] ].join(sep));
299 } else {
300 thisCSV = thisCSV.shift().split(sep).concat(thisCSV);
301 }
302 } else {
303 thisCSV[x].replace(/""/g, '"');
304 }
305 }
306 return thisCSV;
307 };
308
309 // data may be a jQuery object after processing
310 bt.html = function(table, data, wo) {
311 var $t = $(table);
312 if ( data instanceof $ ) {
313 $t.empty().append(data);
314 } else {
315 $t.html(data);
316 }
317 bt.buildComplete(table, wo);
318 };
319
320 /* ==== Object example ====
321 data : {
322 headers : [
323 [
324 { text: 'First Name', class: 'fname', width: '20%' }, // row 1 cell 1
325 'Last Name',
326 { text: 'Age', class: 'age', 'data-sorter' : false },
327 'Total',
328 { text: 'Discount', class : 'sorter-false' },
329 { text: 'Date', class : 'date' } // row 1 cell 6
330 ]
331 ],
332 footers : 'clone', // clone headers or assign array like headers
333 rows : [
334 // TBODY 1
335 [ 'Peter', 'Parker', 28, '$9.99', '20%', 'Jul 6, 2006 8:14 AM' ], // row 1
336 [ 'John', 'Hood', 33, '$19.99', '25%', 'Dec 10, 2002 5:14 AM' ], // row 2
337 [ 'Clark', 'Kent', 18, '$15.89', '44%', 'Jan 12, 2003 11:14 AM' ], // row 3
338
339 // TBODY 2
340 { newTbody: true, class: 'tablesorter-infoOnly' },
341 { cells : [ { text: 'Info Row', colSpan: 6 } ] }, // row 4
342
343 // TBODY 3
344 { newTbody: true },
345 [ 'Bruce', 'Evans', 22, '$13.19', '11%', 'Jan 18, 2007 9:12 AM' ], // row 5
346 [ 'Brice', 'Almighty', 45, '$153.19', '44%', 'Jan 18, 2001 9:12 AM' ], // row 6
347
348 { class: 'specialRow', // row 7
349 cells: [
350 { text: 'Fred', class: 'fname' },
351 { text: 'Smith', class: 'lname' },
352 { text: 18, class: 'age', 'data-info': 'fake ID!, he is really 16' },
353 { text: '$22.44', class: 'total' },
354 { text: '8%', class: 'discount' },
355 { text: 'Aug 20, 2012 10:15 AM', class: 'date' }
356 ],
357 'data-info' : 'This row likes turtles'
358 }
359 ]
360 }
361 */
362 bt.object = function(table, data, wo) {
363 // 'rows'
364 var j, l, t, $c, $t, $tb, $tr,
365 c = table.config,
366 kh = wo.build_objectHeaderKey,
367 kr = wo.build_objectRowKey,
368 h = data.hasOwnProperty(kh) && !$.isEmptyObject(data.kh) ? data.kh : data.hasOwnProperty('headers') ? data.headers : false,
369 r = data.hasOwnProperty(kr) && !$.isEmptyObject(data.kr) ? data.kr : data.hasOwnProperty('rows') ? data.rows : false;
370
371 if (!h || !r || h.length === 0 || r.length === 0) {
372 if (ts.debug(c, 'build')) {
373 console.error('Build >> ERROR: Aborting build table widget, missing data for object build');
374 }
375 return false;
376 }
377
378 $c = $('<colgroup>');
379 $t = $('<table><thead/></table>');
380
381 // Build thead
382 // h = [ ['headerRow1Cell1', 'headerRow1Cell2', ... 'headerRow1CellN' ], ['headerRow2Cell1', ... ] ]
383 // or h = [ [ { text: 'firstCell', class: 'fc', width: '20%' }, ..., { text: 'last Cell' } ], [ /* second row */ ] ]
384 $.each(h, function(i, d) {
385 $tr = $('<tr>').appendTo( $t.find('thead') );
386 l = d.length; // header row
387 for ( j = 0; j < l; j++ ) {
388 // cell(cellData, widgetOptions, 'th', first row)
389 t = bt.build.cell(d[j], wo, 'th', j, i === 0);
390 if (t[0] && t[0].length) { t[0].appendTo( $tr ); } // add cell
391 if (i === 0 && t[1]) { t[1].appendTo( $c ); } // add col to colgroup
392 }
393 });
394 if ($c.find('col[style]').length) {
395 // add colgroup if it contains col elements
396 $t.prepend( $c );
397 }
398
399 $tb = $('<tbody>');
400 // Build tbody
401 $.each(r, function(i, d) {
402 var j;
403 t = $.type(d) === 'object';
404 // add new tbody
405 if (t && d.newTbody) {
406 $tb = $('<tbody>').appendTo( $t );
407 for (j in d) {
408 if (d.hasOwnProperty(j) && j !== 'newTbody') {
409 $tb.attr(j, d[j]);
410 }
411 }
412 } else {
413 if (i === 0) {
414 // add tbody, if the first item in the object isn't a call for a new tbody
415 $tb.appendTo( $t );
416 }
417
418 $tr = $('<tr>').appendTo( $tb );
419 if (t) {
420 // row defined by object
421 for (j in d) {
422 if (d.hasOwnProperty(j) && j !== wo.build_objectCellKey) {
423 $tr.attr(j, d[j]);
424 }
425 }
426 if (d.hasOwnProperty(wo.build_objectCellKey)) {
427 // cells contains each cell info
428 d = d.cells;
429 }
430 }
431
432 l = d.length;
433 for ( j = 0; j < l; j++ ) {
434 // cell(cellData, widgetOptions, 'td')
435 $c = bt.build.cell(d[j], wo, 'td', j);
436 if ($c[0] && $c[0].length) { $c[0].appendTo( $tr ); } // add cell
437 }
438 }
439 });
440
441 // add footer
442 if (data.hasOwnProperty(wo.build_objectFooterKey)) {
443 t = data[wo.build_objectFooterKey];
444 if (t === 'clone') {
445 $c = $t.find('thead').html();
446 $t.append('<tfoot>' + $c + '</tfoot>');
447 } else {
448 $c = $('<tfoot>').appendTo( $t );
449 $.each(t, function(i, d) {
450 $tr = $('<tr>').appendTo( $c );
451 l = d.length; // footer cells
452 for ( j = 0; j < l; j++ ) {
453 // cell(cellData, widgetOptions, 'th')
454 $tb = bt.build.cell(d[j], wo, 'th', j);
455 if ($tb[0] && $tb[0].length) { $tb[0].appendTo( $tr ); } // add cell
456 }
457 });
458 }
459 }
460
461 $(table).html( $t.html() );
462 bt.buildComplete(table, wo);
463 };
464
465 bt.ajax = bt.json = function(table, data, wo) {
466 return bt.object(table, data, wo);
467 };
468
469 })(jQuery);