implement HTML5 file upload; fix is-public display bug
[scpubgit/stemmaweb.git] / root / js / componentload.js
1 // Global state variables
2 var selectedTextID;
3 var selectedTextInfo;
4 var selectedStemmaID = -1;
5 var stemmata = [];
6
7 // Load the names of the appropriate traditions into the directory div.
8 function refreshDirectory () {
9         var lmesg = $('#loading_message').clone();
10         $('#directory').empty().append( lmesg.contents() );
11     $('#directory').load( _get_url(["directory"]), 
12         function(response, status, xhr) {
13                         if (status == "error") {
14                                 var msg = "An error occurred: ";
15                                 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
16                         } else {
17                                 if( textOnLoad != "" ) {
18                                         // Call the click callback for the relevant text, if it is
19                                         // in the page.
20                                         $('#'+textOnLoad).click();
21                                         textOnLoad = "";
22                                 }
23                         }
24                 }
25         );
26 }
27
28 // Load a tradition with its information and stemmata into the tradition
29 // view pane. Calls load_textinfo.
30 function loadTradition( textid, textname, editable ) {
31         selectedTextID = textid;
32     // First insert the placeholder image and register an error handler
33     $('#textinfo_load_status').empty();
34     $('#stemma_graph').empty();
35     $('#textinfo_waitbox').show();
36     $('#textinfo_container').hide().ajaxError( 
37         function(event, jqXHR, ajaxSettings, thrownError) {
38         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET'  ) {
39                         $('#textinfo_waitbox').hide();
40                         $('#textinfo_container').show();
41                         display_error( jqXHR, $("#textinfo_load_status") );
42         }
43     });
44     
45     // Hide the functionality that is irrelevant
46     if( editable ) {
47         $('#open_stemma_add').show();
48         $('#open_stemma_edit').show();
49         $('#open_textinfo_edit').show();
50     } else {
51         $('#open_stemma_add').hide();
52         $('#open_stemma_edit').hide();
53         $('#open_textinfo_edit').hide();
54     }
55
56     // Then get and load the actual content.
57     // TODO: scale #stemma_graph both horizontally and vertically
58     // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
59     $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
60         // Add the scalar data
61         selectedTextInfo = textdata;
62         load_textinfo();
63         // Add the stemma(ta) and set up the stexaminer button
64         stemmata = textdata.stemmata;
65         if( stemmata.length ) {
66                 selectedStemmaID = 0;
67                         $('#run_stexaminer').show();
68         } else {
69                 selectedStemmaID = -1;
70                         $('#open_stemma_edit').hide();
71                         $('#run_stexaminer').hide();
72                 }
73                 load_stemma( selectedStemmaID );
74         // Set up the relationship mapper button
75                 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
76         });
77 }
78
79 // Load the metadata about a tradition into the appropriate div.
80 function load_textinfo() {
81         $('#textinfo_waitbox').hide();
82         $('#textinfo_load_status').empty();
83         $('#textinfo_container').show();
84         $('.texttitle').empty().append( selectedTextInfo.name );
85         // Witnesses
86         $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
87         $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
88         // Who the owner is
89         $('#owner_id').empty().append('no one');
90         if( selectedTextInfo.owner ) {
91                 $('#owner_id').empty().append( selectedTextInfo.owner );
92         }
93         // Whether or not it is public
94         $('#not_public').empty();
95         if( selectedTextInfo['public'] == false ) {
96                 $('#not_public').append('NOT ');
97         }
98         // What language setting it has, if any
99         $('#marked_language').empty().append('no language set');
100         if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
101                 $('#marked_language').empty().append( selectedTextInfo.language );
102         }
103 }       
104
105 // Enable / disable the appropriate buttons for paging through the stemma.
106 function show_stemmapager () {
107       $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
108       $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
109       if( selectedStemmaID > 0 ) {
110               $('.pager_left_button').click( function () {
111                       load_stemma( selectedStemmaID - 1 );
112               }).removeClass( 'greyed_out' );
113       }       
114       if( selectedStemmaID + 1 < stemmata.length ) {
115               $('.pager_right_button').click( function () {
116                       load_stemma( selectedStemmaID + 1 );
117               }).removeClass( 'greyed_out' );
118       }
119 }
120
121 // Load a given stemma SVG into the stemmagraph box.
122 function load_stemma( idx ) {
123         // Load the stemma at idx
124         selectedStemmaID = idx;
125         show_stemmapager();
126         if( idx > -1 ) {
127                 loadSVG( stemmata[idx] );
128                 // Stexaminer submit action
129                 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
130                 $('#run_stexaminer').attr( 'action', stexpath );
131         setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
132         }
133 }
134
135 // Load the SVG we are given
136 function loadSVG(svgData) {
137         var svgElement = $('#stemma_graph');
138
139         $(svgElement).svg('destroy');
140
141         $(svgElement).svg({
142                 loadURL: svgData,
143                 onLoad : function () {
144                         var theSVG = svgElement.find('svg');
145                         var svgoffset = theSVG.offset();
146                         var browseroffset = 1;
147                         // Firefox needs a different offset, stupidly enough
148                         if( navigator.userAgent.indexOf('Firefox') > -1 ) {
149                                 browseroffset = 3; // works for tall images
150                                 // ...but if the SVG is wider than it is tall, Firefox treats
151                                 // the top as being the top of the graph, loaded into the middle
152                                 // of the canvas, but then the margin at the top of the canvas
153                                 // extends upward. So we have to find the actual top of the canvas
154                                 // and correct for *that* instead.
155                                 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
156                                 if( vbdim.height < vbdim.width ) {
157                                         var vbscale = svgElement.width() / vbdim.width;
158                                         var vbrealheight = vbdim.height * vbscale;
159                                         browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
160                                 }
161                         }
162                         var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
163                         theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
164                 }
165         });
166 }
167
168 // General-purpose error-handling function.
169 // TODO make sure this gets used throughout, where appropriate.
170 function display_error( jqXHR, el ) {
171         var errmsg;
172         if( jqXHR.responseText == "" ) {
173                 errmsg = "perhaps the server went down?"
174         } else {
175                 var errobj;
176                 try {
177                         errobj = jQuery.parseJSON( jqXHR.responseText );
178                         errmsg = errobj.error;
179                 } catch ( parse_err ) {
180                         errmsg = "something went wrong on the server."
181                 }
182         }
183         var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
184         $(el).empty().append( msghtml ).show();
185 }
186
187 // Event to enable the upload button when a file has been selected
188 function file_selected( e ) {
189         if( e.files.length == 1 ) {
190                 $('#upload_button').button('enable');
191         } else {
192                 $('#upload_button').button('disable');
193         }
194 }
195
196 function upload_new () {
197         // Serialize the upload form, get the file and attach it to the request,
198         // POST the lot and handle the response.
199         var newfile = $('#new_file').get(0).files[0];
200         var reader = new FileReader();
201         reader.onload = function( evt ) {
202                 var formvals = $('#new_tradition').serializeArray();
203                 var params = { 'file': evt.target.result, 'filename': newfile.name };
204                 $.each( formvals, function( i, o ) {
205                         params[o.name] = o.value;
206                 });
207                 var upload_url = _get_url([ 'newtradition' ]);
208                 $.post( upload_url, params, function( ret ) {
209                         if( ret.id ) {
210                                 $('#upload-collation-dialog').dialog('close');
211                                 refreshDirectory();
212                                 loadTradition( ret.id, ret.name, 1 );
213                         } else if( ret.error ) {
214                                 $('#upload_status').empty().append( 
215                                         $('<span>').attr('class', 'error').append( ret.error ) );
216                         }
217                 });
218         };
219         reader.onerror = function( evt ) {
220                 var err_resp = 'File read error';
221                 if( e.name == 'NotFoundError' ) {
222                         err_resp = 'File not found';
223                 } else if ( e.name == 'NotReadableError' ) {
224                         err_resp == 'File unreadable - is it yours?';
225                 } else if ( e.name == 'EncodingError' ) {
226                         err_resp == 'File cannot be encoded - is it too long?';
227                 } else if ( e.name == 'SecurityError' ) {
228                         err_resp == 'File read security error';
229                 }
230                 // Fake a jqXHR object that we can pass to our generic error handler.
231                 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
232                 display_error( jqxhr, $('#upload_status') );
233                 $('#upload_button').button('disable');
234         }
235         
236         reader.readAsBinaryString( newfile );
237 }
238
239 // Utility function to neatly construct an application URL
240 function _get_url( els ) {
241         return basepath + els.join('/');
242 }
243
244
245 $(document).ready( function() {
246     // call out to load the directory div
247     $('#textinfo_container').hide();
248     $('#textinfo_waitbox').hide();
249         refreshDirectory();
250         
251         // Set up the textinfo edit dialog
252         $('#textinfo-edit-dialog').dialog({
253                 autoOpen: false,
254                 height: 200,
255                 width: 300,
256                 modal: true,
257                 buttons: {
258                         Save: function (evt) {
259                                 $("#edit_textinfo_status").empty();
260                                 $(evt.target).button("disable");
261                                 var requrl = _get_url([ "textinfo", selectedTextID ]);
262                                 var reqparam = $('#edit_textinfo').serialize();
263                                 $.post( requrl, reqparam, function (data) {
264                                         // Reload the selected text fields
265                                         selectedTextInfo = data;
266                                         load_textinfo();
267                                         // Reenable the button and close the form
268                                         $(evt.target).button("enable");
269                                         $('#textinfo-edit-dialog').dialog('close');
270                                 }, 'json' );
271                         },
272                         Cancel: function() {
273                                 $('#textinfo-edit-dialog').dialog('close');
274                         }
275                 },
276                 open: function() {
277                         $("#edit_textinfo_status").empty();
278                         // Populate the form fields with the current values
279                         // edit_(name, language, public, owner)
280                         $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
281                                 var fname = '#edit_' + k;
282                                 // Special case: language Default is basically language null
283                                 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
284                                         $(fname).val( "" );
285                                 } else {
286                                         $(fname).val( selectedTextInfo[k] );
287                                 }
288                         });
289                         if( selectedTextInfo['public'] == true ) {
290                                 $('#edit_public').attr('checked','true');
291                         } else {
292                                 $('#edit_public').removeAttr('checked');
293                         }
294                 },
295         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
296                 $(event.target).parent().find('.ui-button').button("enable");
297         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 
298                 && ajaxSettings.type == 'POST' ) {
299                         display_error( jqXHR, $("#edit_textinfo_status") );
300         }
301         });
302
303         
304         // Set up the stemma editor dialog
305         $('#stemma-edit-dialog').dialog({
306                 autoOpen: false,
307                 height: 700,
308                 width: 600,
309                 modal: true,
310                 buttons: {
311                         Save: function (evt) {
312                                 $("#edit_stemma_status").empty();
313                                 $(evt.target).button("disable");
314                                 var stemmaseq = $('#stemmaseq').val();
315                                 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
316                                 var reqparam = { 'dot': $('#dot_field').val() };
317                                 // TODO We need to stash the literal SVG string in stemmata
318                                 // somehow. Implement accept header on server side to decide
319                                 // whether to send application/json or application/xml?
320                                 $.post( requrl, reqparam, function (data) {
321                                         // We received a stemma SVG string in return. 
322                                         // Update the current stemma sequence number
323                                         selectedStemmaID = data.stemmaid;
324                                         // Stash the answer in our SVG array
325                                         stemmata[selectedStemmaID] = data.stemmasvg;
326                                         // Display the new stemma
327                                         load_stemma( selectedStemmaID );
328                                         // Reenable the button and close the form
329                                         $(evt.target).button("enable");
330                                         $('#stemma-edit-dialog').dialog('close');
331                                 }, 'json' );
332                         },
333                         Cancel: function() {
334                                 $('#stemma-edit-dialog').dialog('close');
335                         }
336                 },
337                 open: function(evt) {
338                         $("#edit_stemma_status").empty();
339                         var stemmaseq = $('#stemmaseq').val();
340                         if( stemmaseq == 'n' ) {
341                                 // If we are creating a new stemma, populate the textarea with a
342                                 // bare digraph.
343                                 $(evt.target).dialog('option', 'title', 'Add a new stemma')
344                                 $('#dot_field').val( "digraph stemma {\n\n}" );
345                         } else {
346                                 // If we are editing a stemma, grab its stemmadot and populate the
347                                 // textarea with that.
348                                 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
349                                 $('#dot_field').val( 'Loading, please wait...' );
350                                 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
351                                 $.getJSON( doturl, function (data) {
352                                         // Re-insert the line breaks
353                                         var dotstring = data.dot.replace(/\|n/gm, "\n");                                        
354                                         $('#dot_field').val( dotstring );
355                                 });
356                         }
357                 },
358         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
359                 $(event.target).parent().find('.ui-button').button("enable");
360         if( ajaxSettings.url.indexOf( 'stemma' ) > -1 
361                 && ajaxSettings.type == 'POST' ) {
362                         display_error( jqXHR, $("#edit_stemma_status") );
363         }
364         });
365                 
366         $('#upload-collation-dialog').dialog({
367                 autoOpen: false,
368                 height: 360,
369                 width: 480,
370                 modal: true,
371                 buttons: {
372                   upload: {
373                     text: 'Upload',
374                     id: 'upload_button',
375                     click: function() {
376                             $('#upload_status').empty();
377                             $('#upload_button').button("disable");
378                 upload_new();
379             }
380                   },
381                   Cancel: function() {
382                     $('#upload-collation-dialog').dialog('close');
383                   }
384                 },
385                 open: function() {
386                         // Set the upload button to its correct state based on
387                         // whether a file is loaded
388                         file_selected( $('#new_file').get(0) );
389                 }
390         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
391                 // Reset button state
392                 file_selected( $('#new_file').get(0) );
393                 // Display error message if applicable
394         if( ajaxSettings.url.indexOf( 'newtradition' ) > -1 
395                 && ajaxSettings.type == 'POST' ) {
396                         display_error( jqXHR, $("#upload_status") );
397         }
398         });;
399         
400         $('#stemma_graph').mousedown( function(evt) {
401         evt.stopPropagation();
402         $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
403         $('body').mousemove( function(evt) {
404             mouse_scale = 1; // for now, was:  mouse_scale = svg_root_element.getScreenCTM().a;
405             dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
406             dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
407             $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
408             var svg_root = $('#stemma_graph svg').svg().svg('get').root();
409             var g = $('g.graph', svg_root).get(0);
410             current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
411             new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
412             g.setAttribute( 'transform', new_transform );
413             evt.returnValue = false;
414             evt.preventDefault();
415             return false;
416         });
417         $('body').mouseup( function(evt) {
418             $('body').unbind('mousemove');
419             $('body').unbind('mouseup');
420         });
421         });
422          
423         $('#stemma_graph').mousewheel(function (event, delta) {
424         event.returnValue = false;
425         event.preventDefault();
426         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
427         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
428         if( delta < -9 ) { delta = -9 }; 
429         var z = 1 + delta/10;
430         z = delta > 0 ? 1 : -1;
431         var svg_root = $('#stemma_graph svg').svg().svg('get').root();
432         var g = $('g.graph', svg_root).get(0);
433         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
434             var scaleLevel = z/10;
435             current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
436             new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
437             g.setAttribute( 'transform', new_transform );
438         }
439     });
440     
441 });