1 ( function( $, app, joey ) {
5 var CELL_SEPARATOR = ",";
7 var LINE_SEPARATOR = "\r\n";
9 ui.CSVTable = ui.AbstractWidget.extend({
13 _baseCls: "uiCSVTable",
14 init: function( parent ) {
16 var results = this.config.results.hits.hits;
17 var columns = this._parseResults( results );
18 this._downloadButton = new ui.Button({
19 label: "Generate Download Link",
20 onclick: this._downloadLinkGenerator_handler
22 this._downloadLink = $.joey( { tag: "A", text: "download", });
23 this._downloadLink.hide();
24 this._csvText = this._csv_template( columns, results );
25 this.el = $.joey( this._main_template() );
26 this.attach( parent );
28 _downloadLinkGenerator_handler: function() {
29 var csvData = new Blob( [ this._csvText ], { type: 'text/csv' });
30 var csvURL = URL.createObjectURL( csvData );
31 this._downloadLink.attr( "href", csvURL );
32 this._downloadLink.show();
34 _parseResults: function( results ) {
36 (function parse( path, obj ) {
37 if( obj instanceof Array ) {
38 for( var i = 0; i < obj.length; i++ ) {
39 parse( path, obj[i] );
41 } else if( typeof obj === "object" ) {
42 for( var prop in obj ) {
43 parse( path + "." + prop, obj[ prop ] );
46 columnPaths[ path ] = true;
48 })( "root", results );
50 for( var column in columnPaths ) {
51 columns.push( column.split(".").slice(1) );
55 _main_template: function() { return (
56 { tag: "DIV", cls: this._baseCls, id: this.id(), children: [
59 { tag: "PRE", text: this._csvText }
62 _csv_template: function( columns, results ) {
63 return this._header_template( columns ) + LINE_SEPARATOR + this._results_template( columns, results );
65 _header_template: function( columns ) {
66 return columns.map( function( column ) {
67 return column.join(".");
68 }).join( CELL_SEPARATOR );
70 _results_template: function( columns, results ) {
71 return results.map( function( result ) {
72 return columns.map( function( column ) {
75 while( l !== column.length && ptr != null ) {
76 ptr = ptr[ column[ l++ ] ];
78 return ( ptr == null ) ? "" : ( CELL_QUOTE + ptr.toString().replace(/"/g, '""') + CELL_QUOTE );
79 }).join( CELL_SEPARATOR );
80 }).join( LINE_SEPARATOR );
84 })( this.jQuery, this.app, this.joey );