2 * Copyright 2010-2013 Ben Birch
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this software except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 ( function( $, app, joey ) {
18 var ui = app.ns("ui");
20 var CELL_SEPARATOR = ",";
22 var LINE_SEPARATOR = "\r\n";
24 ui.CSVTable = ui.AbstractWidget.extend({
28 _baseCls: "uiCSVTable",
29 init: function( parent ) {
31 var results = this.config.results.hits.hits;
32 var columns = this._parseResults( results );
33 this._downloadButton = new ui.Button({
34 label: "Generate Download Link",
35 onclick: this._downloadLinkGenerator_handler
37 this._downloadLink = $.joey( { tag: "A", text: "download", });
38 this._downloadLink.hide();
39 this._csvText = this._csv_template( columns, results );
40 this.el = $.joey( this._main_template() );
41 this.attach( parent );
43 _downloadLinkGenerator_handler: function() {
44 var csvData = new Blob( [ this._csvText ], { type: 'text/csv' });
45 var csvURL = URL.createObjectURL( csvData );
46 this._downloadLink.attr( "href", csvURL );
47 this._downloadLink.show();
49 _parseResults: function( results ) {
51 (function parse( path, obj ) {
52 if( obj instanceof Array ) {
53 for( var i = 0; i < obj.length; i++ ) {
54 parse( path, obj[i] );
56 } else if( typeof obj === "object" ) {
57 for( var prop in obj ) {
58 parse( path + "." + prop, obj[ prop ] );
61 columnPaths[ path ] = true;
63 })( "root", results );
65 for( var column in columnPaths ) {
66 columns.push( column.split(".").slice(1) );
70 _main_template: function() { return (
71 { tag: "DIV", cls: this._baseCls, id: this.id(), children: [
74 { tag: "PRE", text: this._csvText }
77 _csv_template: function( columns, results ) {
78 return this._header_template( columns ) + LINE_SEPARATOR + this._results_template( columns, results );
80 _header_template: function( columns ) {
81 return columns.map( function( column ) {
82 return column.join(".");
83 }).join( CELL_SEPARATOR );
85 _results_template: function( columns, results ) {
86 return results.map( function( result ) {
87 return columns.map( function( column ) {
90 while( l !== column.length && ptr != null ) {
91 ptr = ptr[ column[ l++ ] ];
93 return ( ptr == null ) ? "" : ( CELL_QUOTE + ptr.toString().replace(/"/g, '""') + CELL_QUOTE );
94 }).join( CELL_SEPARATOR );
95 }).join( LINE_SEPARATOR );
99 })( this.jQuery, this.app, this.joey );