Debian Codegraph @

js/widgets/widget-output.js

raw symbols SCIP
1 /*! Widget: output - updated 9/27/2017 (v2.29.0) *//*
2 * Requires tablesorter v2.8+ and jQuery 1.7+
3 * Modified from:
4 * HTML Table to CSV: http://www.kunalbabre.com/projects/table2CSV.php (License unknown?)
5 * Download-File-JS: https://github.com/PixelsCommander/Download-File-JS (http://www.apache.org/licenses/LICENSE-2.0)
6 * FileSaver.js: https://github.com/eligrey/FileSaver.js (MIT)
7 */
8 /*jshint browser:true, jquery:true, unused:false */
9 /*global jQuery:false, alert:false */
10 ;(function($) {
11 'use strict';
12
13 var ts = $.tablesorter,
14
15 output = ts.output = {
16
17 event : 'outputTable',
18 // Double click time is about 500ms; this value ignores double clicks
19 // and prevents multiple windows from opening - issue in Firefox
20 noDblClick : 600, // ms
21 lastEvent : 0,
22 // prevent overlapping multiple opens in case rendering of content in
23 // popup or download is longer than noDblClick time.
24 busy : false,
25
26 // wrap line breaks & tabs in quotes
27 regexQuote : /([\n\t\x09\x0d\x0a]|<[^<]+>)/, // test if cell needs wrapping quotes
28 regexBR : /(<br([\s\/])?>|\n)/g, // replace
29 regexIMG : /<img[^>]+alt\s*=\s*['"]([^'"]+)['"][^>]*>/i, // match
30 regexHTML : /<[^<]+>/g, // replace
31
32 replaceCR : '\x0d\x0a',
33 replaceTab : '\x09',
34
35 popupTitle : 'Output',
36 popupStyle : 'width:100%;height:100%;margin:0;resize:none;', // for textarea
37 message : 'Your device does not support downloading. Please try again in desktop browser.',
38
39 init : function(c) {
40 c.$table
41 .off(output.event)
42 .on(output.event, function( e ) {
43 e.stopPropagation();
44 // prevent multiple windows opening
45 if (
46 !output.busy &&
47 (e.timeStamp - output.lastEvent > output.noDblClick)
48 ) {
49 output.lastEvent = e.timeStamp;
50 output.busy = true;
51 // explicitly use table.config.widgetOptions because we want
52 // the most up-to-date values; not the 'wo' from initialization
53 output.process(c, c.widgetOptions);
54 }
55 });
56 },
57
58 processRow: function(c, $rows, isHeader, isJSON) {
59 var $cell, $cells, cellsLen, rowIndex, row, col, indx, rowspanLen, colspanLen, txt,
60 wo = c.widgetOptions,
61 tmpRow = [],
62 dupe = wo.output_duplicateSpans,
63 addSpanIndex = isHeader && isJSON && wo.output_headerRows && $.isFunction(wo.output_callbackJSON),
64 cellIndex = 0,
65 rowsLength = $rows.length;
66
67 for ( rowIndex = 0; rowIndex < rowsLength; rowIndex++ ) {
68 if (!tmpRow[rowIndex]) { tmpRow[rowIndex] = []; }
69 cellIndex = 0;
70 $cells = $rows.eq( rowIndex ).children();
71 cellsLen = $cells.length;
72 for ( indx = 0; indx < cellsLen; indx++ ) {
73 $cell = $cells.eq( indx );
74 // process rowspans
75 if ($cell.filter('[rowspan]').length) {
76 rowspanLen = parseInt( $cell.attr('rowspan'), 10) - 1;
77 txt = output.formatData( c, wo, $cell, isHeader, indx );
78 for (row = 1; row <= rowspanLen; row++) {
79 if (!tmpRow[rowIndex + row]) { tmpRow[rowIndex + row] = []; }
80 tmpRow[rowIndex + row][cellIndex] = isHeader ? txt : dupe ? txt : '';
81 }
82 }
83 // process colspans
84 if ($cell.filter('[colspan]').length) {
85 colspanLen = parseInt( $cell.attr('colspan'), 10) - 1;
86 // allow data-attribute to be an empty string
87 txt = output.formatData( c, wo, $cell, isHeader, indx );
88 for (col = 0; col < colspanLen; col++) {
89 // if we're processing the header & making JSON, the header names need to be unique
90 if ($cell.filter('[rowspan]').length) {
91 rowspanLen = parseInt( $cell.attr('rowspan'), 10);
92 for (row = 0; row < rowspanLen; row++) {
93 if (!tmpRow[rowIndex + row]) { tmpRow[rowIndex + row] = []; }
94 tmpRow[rowIndex + row][cellIndex + col] = addSpanIndex ?
95 wo.output_callbackJSON($cell, txt, cellIndex + col) ||
96 txt + '(' + (cellIndex + col) + ')' : isHeader ? txt : dupe ? txt : '';
97 }
98 } else {
99 tmpRow[rowIndex][cellIndex + col] = addSpanIndex ?
100 wo.output_callbackJSON($cell, txt, cellIndex + col) ||
101 txt + '(' + (cellIndex + col) + ')' : isHeader ? txt : dupe ? txt : '';
102 }
103 }
104 }
105
106 // skip column if already defined
107 while (typeof tmpRow[rowIndex][cellIndex] !== 'undefined') { cellIndex++; }
108
109 tmpRow[rowIndex][cellIndex] = tmpRow[rowIndex][cellIndex] ||
110 output.formatData( c, wo, $cell, isHeader, cellIndex );
111 cellIndex++;
112 }
113 }
114 return ts.output.removeColumns( c, wo, tmpRow );
115 },
116
117 // remove hidden/ignored columns
118 removeColumns : function( c, wo, arry ) {
119 var rowIndex, row, colIndex,
120 data = [],
121 len = arry.length;
122 for ( rowIndex = 0; rowIndex < len; rowIndex++ ) {
123 row = arry[ rowIndex ];
124 data[ rowIndex ] = [];
125 for ( colIndex = 0; colIndex < c.columns; colIndex++ ) {
126 if ( !wo.output_hiddenColumnArray[ colIndex ] ) {
127 data[ rowIndex ].push( row[ colIndex ] );
128 }
129 }
130 }
131 return data;
132 },
133
134 // optional vars $rows and dump added by TheSin to make
135 // process callable via callback for ajaxPager
136 process : function(c, wo, $rows, dump) {
137 var mydata, $this, headers, csvData, len, rowsLen, tmp,
138 hasStringify = window.JSON && JSON.hasOwnProperty('stringify'),
139 indx = 0,
140 tmpData = (wo.output_separator || ',').toLowerCase(),
141 outputJSON = tmpData === 'json',
142 outputArray = tmpData === 'array',
143 separator = outputJSON || outputArray ? ',' : wo.output_separator,
144 saveRows = wo.output_saveRows,
145 $el = c.$table;
146 // regex to look for the set separator or HTML
147 wo.output_regex = new RegExp('(' + (/\\/.test(separator) ? '\\' : '' ) + separator + ')' );
148
149 // make a list of hidden columns
150 wo.output_hiddenColumnArray = [];
151 for ( indx = 0; indx < c.columns; indx++ ) {
152 wo.output_hiddenColumnArray[ indx ] = $.inArray( indx, wo.output_ignoreColumns ) > -1 ||
153 ( !wo.output_hiddenColumns && c.$headerIndexed[ indx ].css( 'display' ) === 'none' &&
154 !c.$headerIndexed[ indx ].hasClass( 'tablesorter-scroller-hidden-column' ) );
155 }
156
157 // get header cells
158 $this = $el
159 .children('thead').children('tr')
160 .not('.' + (ts.css.filterRow || 'tablesorter-filter-row') )
161 .filter( function() {
162 return wo.output_hiddenColumns || $(this).css('display') !== 'none';
163 });
164 headers = output.processRow(c, $this, true, outputJSON);
165
166 // all tbody rows - do not include widget added rows (e.g. grouping widget headers)
167 if ( !$rows ) {
168 $rows = $el.children('tbody').children('tr').not(c.selectorRemove);
169 }
170
171 // check for a filter callback function first! because
172 // /^f/.test(function() { console.log('test'); }) is TRUE! (function is converted to a string)
173 $rows = typeof saveRows === 'function' ? $rows.filter(saveRows) :
174 // get (f)iltered, (v)isible, all rows (look for the first letter only), or jQuery filter selector
175 /^f/.test(saveRows) ? $rows.not('.' + (wo.filter_filteredRow || 'filtered') ) :
176 /^v/.test(saveRows) ? $rows.filter(':visible') :
177 // look for '.' (class selector), '#' (id selector),
178 // ':' (basic filters, e.g. ':not()') or '[' (attribute selector start)
179 /^[.#:\[]/.test(saveRows) ? $rows.filter(saveRows) :
180 // default to all rows
181 $rows;
182
183 // process to array of arrays
184 csvData = output.processRow(c, $rows);
185 if (wo.output_includeFooter) {
186 // clone, to force the tfoot rows to the end of this selection of rows
187 // otherwise they appear after the thead (the order in the HTML)
188 csvData = csvData.concat( output.processRow( c, $el.children('tfoot').children('tr:visible') ) );
189 }
190
191 len = headers.length;
192
193 if (outputJSON) {
194 tmpData = [];
195 rowsLen = csvData.length;
196 for ( indx = 0; indx < rowsLen; indx++ ) {
197 // multiple header rows & output_headerRows = true, pick the last row...
198 tmp = headers[ ( len > 1 && wo.output_headerRows ) ? indx % len : len - 1 ];
199 tmpData.push( output.row2Hash( tmp, csvData[ indx ] ) );
200 }
201
202 // requires JSON stringify; if it doesn't exist, the output will show [object Object],... in the output window
203 mydata = hasStringify ? JSON.stringify(tmpData) : tmpData;
204 } else {
205 if (wo.output_includeHeader) {
206 tmp = [ headers[ ( len > 1 && wo.output_headerRows ) ? indx % len : len - 1 ] ];
207 tmpData = output.row2CSV(wo, wo.output_headerRows ? headers : tmp, outputArray)
208 .concat( output.row2CSV(wo, csvData, outputArray) );
209 } else {
210 tmpData = output.row2CSV(wo, csvData, outputArray);
211 }
212
213 // stringify the array; if stringify doesn't exist the array will be flattened
214 mydata = outputArray && hasStringify ? JSON.stringify(tmpData) : tmpData.join('\n');
215 }
216
217 if (dump) {
218 return mydata;
219 }
220
221 // callback; if true returned, continue processing
222 if ($.isFunction(wo.output_callback)) {
223 tmp = wo.output_callback(c, mydata, c.pager && c.pager.ajaxObject.url || null);
224 if ( tmp === false ) {
225 output.busy = false;
226 return;
227 } else if ( typeof tmp === 'string' ) {
228 mydata = tmp;
229 }
230 }
231
232 if ( /p/i.test( wo.output_delivery || '' ) ) {
233 output.popup(mydata, wo.output_popupStyle, outputJSON || outputArray);
234 } else {
235 output.download(c, wo, mydata);
236 }
237 output.busy = false;
238
239 }, // end process
240
241 row2CSV : function(wo, tmpRow, outputArray) {
242 var tmp, rowIndex,
243 csvData = [],
244 rowLen = tmpRow.length;
245 for (rowIndex = 0; rowIndex < rowLen; rowIndex++) {
246 // remove any blank rows
247 tmp = ( tmpRow[rowIndex] || [] ).join('').replace(/\"/g, '');
248 if ( ( tmpRow[rowIndex] || [] ).length > 0 && tmp !== '' ) {
249 csvData[csvData.length] = outputArray ? tmpRow[rowIndex] : tmpRow[rowIndex].join(wo.output_separator);
250 }
251 }
252 return csvData;
253 },
254
255 row2Hash : function( keys, values ) {
256 var indx,
257 json = {},
258 len = values.length;
259 for ( indx = 0; indx < len; indx++ ) {
260 if ( indx < keys.length ) {
261 json[ keys[ indx ] ] = values[ indx ];
262 }
263 }
264 return json;
265 },
266
267 formatData : function(c, wo, $el, isHeader, colIndex) {
268 var attr = $el.attr(wo.output_dataAttrib),
269 txt = typeof attr !== 'undefined' ? attr : $el.html(),
270 quotes = (wo.output_separator || ',').toLowerCase(),
271 separator = quotes === 'json' || quotes === 'array',
272 // replace " with “ if undefined
273 result = txt.replace(/\"/g, wo.output_replaceQuote || '\u201c');
274 // replace line breaks with \\n & tabs with \\t
275 if (!wo.output_trimSpaces) {
276 result = result.replace(output.regexBR, output.replaceCR).replace(/\t/g, output.replaceTab);
277 } else {
278 result = result.replace(output.regexBR, '');
279 }
280 // extract img alt text
281 txt = result.match(output.regexIMG);
282 if (!wo.output_includeHTML && txt !== null) {
283 result = txt[1];
284 }
285 // replace/remove html
286 result = wo.output_includeHTML && !isHeader ? result : result.replace(output.regexHTML, '');
287 result = wo.output_trimSpaces || isHeader ? $.trim(result) : result;
288 // JSON & array outputs don't need quotes
289 quotes = separator ? false : wo.output_wrapQuotes || wo.output_regex.test(result) || output.regexQuote.test(result);
290 result = quotes ? '"' + result + '"' : result;
291 // formatting callback - added v2.22.4
292 if ( typeof wo.output_formatContent === 'function' ) {
293 return wo.output_formatContent( c, wo, {
294 isHeader : isHeader || false,
295 $cell : $el,
296 content : result,
297 columnIndex: colIndex,
298 parsed: c.parsers[colIndex].format(result, c.table, $el[0], colIndex)
299 });
300 }
301
302 return result;
303 },
304
305 popup : function(data, style, wrap) {
306 var generator = window.open('', output.popupTitle, style);
307 try {
308 generator.document.write(
309 '<html><head><title>' + output.popupTitle + '</title></head><body>' +
310 '<textarea wrap="' + (wrap ? 'on' : 'off') + '" style="' +
311 output.popupStyle + '">' + data + '\n</textarea>' +
312 '</body></html>'
313 );
314 generator.document.close();
315 generator.focus();
316 } catch (e) {
317 // popup already open
318 generator.close();
319 return output.popup(data, style, wrap);
320 }
321 // select all text and focus within the textarea in the popup
322 // $(generator.document).find('textarea').select().focus();
323 return true;
324 },
325
326 // modified from https://github.com/PixelsCommander/Download-File-JS
327 // & http://html5-demos.appspot.com/static/a.download.html
328 download : function (c, wo, data) {
329
330 if (typeof wo.output_savePlugin === 'function') {
331 return wo.output_savePlugin(c, wo, data);
332 }
333
334 var e, blob, gotBlob, bom,
335 nav = window.navigator,
336 link = document.createElement('a');
337
338 // iOS devices do not support downloading. We have to inform user about
339 // this limitation.
340 if (/(iP)/g.test(nav.userAgent)) {
341 alert(output.message);
342 return false;
343 }
344
345 // test for blob support
346 try {
347 gotBlob = !!new Blob();
348 } catch (err) {
349 gotBlob = false;
350 }
351
352 // Use HTML5 Blob if browser supports it
353 if ( gotBlob ) {
354
355 window.URL = window.URL || window.webkitURL;
356 // prepend BOM for UTF-8 XML and text/* types (including HTML)
357 // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
358 // see https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js#L68
359 bom = (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(wo.output_encoding)) ?
360 [ '\ufeff', data ] : [ data ];
361 blob = new Blob( bom, { type: wo.output_encoding } );
362
363 if (nav.msSaveBlob) {
364 // IE 10+
365 nav.msSaveBlob(blob, wo.output_saveFileName);
366 } else {
367 // all other browsers
368 link.href = window.URL.createObjectURL(blob);
369 link.download = wo.output_saveFileName;
370 // Dispatching click event; using $(link).trigger() won't work
371 if (document.createEvent) {
372 e = document.createEvent('MouseEvents');
373 // event.initMouseEvent(type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY,
374 // ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget);
375 e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
376 link.dispatchEvent(e);
377 }
378 }
379 return false;
380 }
381
382 // fallback to force file download (whether supported by server).
383 // not sure if this actually works in IE9 and older...
384 window.open( wo.output_encoding + encodeURIComponent(data) + '?download', '_self');
385 return true;
386
387 },
388
389 remove : function(c) {
390 c.$table.off(output.event);
391 }
392
393 };
394
395 ts.addWidget({
396 id: 'output',
397 options: {
398 output_separator : ',', // set to 'json', 'array' or any separator
399 output_ignoreColumns : [], // columns to ignore [0, 1,... ] (zero-based index)
400 output_hiddenColumns : false, // include hidden columns in the output
401 output_includeFooter : false, // include footer rows in the output
402 output_includeHeader : true, // include header rows in the output
403 output_headerRows : false, // if true, include multiple header rows
404 output_dataAttrib : 'data-name', // header attrib containing modified header name
405 output_delivery : 'popup', // popup, download
406 output_saveRows : 'filtered', // (a)ll, (v)isible, (f)iltered or jQuery filter selector
407 output_duplicateSpans : true, // duplicate output data in tbody colspan/rowspan
408 output_replaceQuote : '\u201c;', // left double quote
409 output_includeHTML : false,
410 output_trimSpaces : true,
411 output_wrapQuotes : false,
412 output_popupStyle : 'width=500,height=300',
413 output_saveFileName : 'mytable.csv',
414 // format $cell content callback
415 output_formatContent : null, // function(config, widgetOptions, data) { return data.content; }
416 // callback executed when processing completes
417 // return true to continue download/output
418 // return false to stop delivery & do something else with the data
419 output_callback : function(/* config, data */) { return true; },
420 // JSON callback executed when a colspan is encountered in the header
421 output_callbackJSON : function($cell, txt, cellIndex) { return txt + '(' + (cellIndex) + ')'; },
422 // the need to modify this for Excel no longer exists
423 output_encoding : 'data:application/octet-stream;charset=utf8,',
424 // override internal save file code and use an external plugin such as
425 // https://github.com/eligrey/FileSaver.js
426 output_savePlugin : null /* function(c, wo, data) {
427 var blob = new Blob([data], {type: wo.output_encoding});
428 saveAs(blob, wo.output_saveFileName);
429 } */
430 },
431 init: function(table, thisWidget, c) {
432 output.init(c);
433 },
434 remove: function(table, c) {
435 output.remove(c);
436 }
437
438 });
439
440 })(jQuery);