Make stemma data return consistent; refrain from assuming digraph in edit box. Fixes #28
[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         $('#relatebutton_label').text('View collation and edit relationships');
51     } else {
52         $('#open_stemma_add').hide();
53         $('#open_stemma_edit').hide();
54         $('#open_textinfo_edit').hide();
55         $('#relatebutton_label').text('View collation and relationships');
56     }
57
58     // Then get and load the actual content.
59     // TODO: scale #stemma_graph both horizontally and vertically
60     // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
61     $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
62         // Add the scalar data
63         selectedTextInfo = textdata;
64         load_textinfo();
65         // Add the stemma(ta) and set up the stexaminer button
66         stemmata = textdata.stemmata;
67         if( stemmata.length ) {
68                 selectedStemmaID = 0;
69                         $('#run_stexaminer').show();
70         } else {
71                 selectedStemmaID = -1;
72                         $('#open_stemma_edit').hide();
73                         $('#run_stexaminer').hide();
74                 }
75                 load_stemma( selectedStemmaID );
76         // Set up the relationship mapper button
77                 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
78                 // Set up the download button
79                 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
80                 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
81         });
82 }
83
84 // Load the metadata about a tradition into the appropriate div.
85 function load_textinfo() {
86         $('#textinfo_waitbox').hide();
87         $('#textinfo_load_status').empty();
88         $('#textinfo_container').show();
89         $('.texttitle').empty().append( selectedTextInfo.name );
90         // Witnesses
91         $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
92         $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
93         // Who the owner is
94         $('#owner_id').empty().append('no one');
95         if( selectedTextInfo.owner ) {
96                 var owneremail = selectedTextInfo.owner;
97                 var chop = owneremail.indexOf( '@' );
98                 if( chop > -1 ) {
99                         owneremail = owneremail.substr( 0, chop + 1 ) + '...';
100                 }
101                 $('#owner_id').empty().append( owneremail );
102         }
103         // Whether or not it is public
104         $('#not_public').empty();
105         if( selectedTextInfo['public'] == false ) {
106                 $('#not_public').append('NOT ');
107         }
108         // What language setting it has, if any
109         $('#marked_language').empty().append('no language set');
110         if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
111                 $('#marked_language').empty().append( selectedTextInfo.language );
112         }
113 }       
114
115 // Enable / disable the appropriate buttons for paging through the stemma.
116 function show_stemmapager () {
117       $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
118       $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
119       if( selectedStemmaID > 0 ) {
120               $('.pager_left_button').click( function () {
121                       load_stemma( selectedStemmaID - 1 );
122               }).removeClass( 'greyed_out' );
123       }       
124       if( selectedStemmaID + 1 < stemmata.length ) {
125               $('.pager_right_button').click( function () {
126                       load_stemma( selectedStemmaID + 1 );
127               }).removeClass( 'greyed_out' );
128       }
129 }
130
131 // Load a given stemma SVG into the stemmagraph box.
132 function load_stemma( idx ) {
133         // Load the stemma at idx
134         selectedStemmaID = idx;
135         show_stemmapager();
136         if( idx > -1 ) {
137                 // Load the SVG and identifier of the stemma
138                 var stemmadata = stemmata[idx];
139                 loadSVG( stemmadata['svg'] );
140                 $('#stemma_identifier').empty().text( stemmadata['name'] );
141                 // Stexaminer submit action
142                 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
143                 $('#run_stexaminer').attr( 'action', stexpath );
144         setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
145         }
146 }
147
148 // Load the SVG we are given
149 function loadSVG(svgData) {
150         var svgElement = $('#stemma_graph');
151
152         $(svgElement).svg('destroy');
153
154         $(svgElement).svg({
155                 loadURL: svgData,
156                 onLoad : function () {
157                         var theSVG = svgElement.find('svg');
158                         var svgoffset = theSVG.offset();
159                         var browseroffset = 1;
160                         // Firefox needs a different offset, stupidly enough
161                         if( navigator.userAgent.indexOf('Firefox') > -1 ) {
162                                 browseroffset = 3; // works for tall images
163                                 // ...but if the SVG is wider than it is tall, Firefox treats
164                                 // the top as being the top of the graph, loaded into the middle
165                                 // of the canvas, but then the margin at the top of the canvas
166                                 // extends upward. So we have to find the actual top of the canvas
167                                 // and correct for *that* instead.
168                                 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
169                                 if( vbdim.height < vbdim.width ) {
170                                         var vbscale = svgElement.width() / vbdim.width;
171                                         var vbrealheight = vbdim.height * vbscale;
172                                         browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
173                                 }
174                         }
175                         var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
176                         theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
177                 }
178         });
179 }
180
181 // General-purpose error-handling function.
182 // TODO make sure this gets used throughout, where appropriate.
183 function display_error( jqXHR, el ) {
184         var errmsg;
185         if( jqXHR.responseText == "" ) {
186                 errmsg = "perhaps the server went down?"
187         } else {
188                 var errobj;
189                 try {
190                         errobj = jQuery.parseJSON( jqXHR.responseText );
191                         errmsg = errobj.error;
192                 } catch ( parse_err ) {
193                         errmsg = "something went wrong on the server."
194                 }
195         }
196         var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
197         $(el).empty().append( msghtml ).show();
198 }
199
200 // Event to enable the upload button when a file has been selected
201 function file_selected( e ) {
202         if( e.files.length == 1 ) {
203                 $('#upload_button').button('enable');
204                 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
205         } else {
206                 $('#upload_button').button('disable');
207                 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
208         }
209 }
210
211 // Implement our own AJAX method that uses the features of XMLHttpRequest2
212 // but try to let it have a similar interface to jquery.post
213 // The data var needs to be a FormData() object.
214 // The callback will be given a single argument, which is the response data
215 // of the given type.
216
217 function post_xhr2( url, data, cb, type ) {
218         if( !type ) {
219                 type = 'json';
220         }
221         var xhr = new XMLHttpRequest();
222         // Set the expected response type
223         if( type === 'data' ) {
224                 xhr.responseType = 'blob';
225         } else if( type === 'xml' ) {
226                 xhr.responseType = 'document';
227         } 
228         // Post the form
229         // Gin up an AJAX settings object
230         $.ajaxSetup({ url: url, type: 'POST' });
231         xhr.open( 'POST', url, true );
232         // Handle the results
233         xhr.onload = function( e ) {
234                 // Get the response and parse it
235                 // Call the callback with the response, whatever it was
236                 var xhrs = e.target;
237                 if( xhrs.status > 199 && xhrs.status < 300  ) { // Success
238                         var resp;
239                         if( type === 'json' ) {
240                                 resp = $.parseJSON( xhrs.responseText );
241                         } else if ( type === 'xml' ) {
242                                 resp = xhrs.responseXML;
243                         } else if ( type === 'text' ) {
244                                 resp = xhrs.responseText;
245                         } else {
246                                 resp = xhrs.response;
247                         }
248                         cb( resp );
249                 } else {
250                         // Trigger the ajaxError...
251                         _trigger_ajaxerror( e );
252                 }
253         };
254         xhr.onerror = _trigger_ajaxerror;
255         xhr.onabort = _trigger_ajaxerror;
256         xhr.send( data );
257 }
258
259 function _trigger_ajaxerror( e ) {
260         var xhr = e.target;
261         var thrown = xhr.statusText || 'Request error';
262         jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
263 }
264
265 function upload_new () {
266         // Serialize the upload form, get the file and attach it to the request,
267         // POST the lot and handle the response.
268         var newfile = $('#new_file').get(0).files[0];
269         var reader = new FileReader();
270         reader.onload = function( evt ) {
271                 var data = new FormData();
272                 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
273                                 data.append( o.name, o.value );
274                         });
275                 data.append( 'file', newfile );
276                 var upload_url = _get_url([ 'newtradition' ]);
277                 post_xhr2( upload_url, data, function( ret ) {
278                         if( ret.id ) {
279                                 $('#upload-collation-dialog').dialog('close');
280                                 refreshDirectory();
281                                 loadTradition( ret.id, ret.name, 1 );
282                         } else if( ret.error ) {
283                                 $('#upload_status').empty().append( 
284                                         $('<span>').attr('class', 'error').append( ret.error ) );
285                         }
286                 }, 'json' );
287         };
288         reader.onerror = function( evt ) {
289                 var err_resp = 'File read error';
290                 if( e.name == 'NotFoundError' ) {
291                         err_resp = 'File not found';
292                 } else if ( e.name == 'NotReadableError' ) {
293                         err_resp == 'File unreadable - is it yours?';
294                 } else if ( e.name == 'EncodingError' ) {
295                         err_resp == 'File cannot be encoded - is it too long?';
296                 } else if ( e.name == 'SecurityError' ) {
297                         err_resp == 'File read security error';
298                 }
299                 // Fake a jqXHR object that we can pass to our generic error handler.
300                 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
301                 display_error( jqxhr, $('#upload_status') );
302                 $('#upload_button').button('disable');
303         }
304         
305         reader.readAsBinaryString( newfile );
306 }
307
308 // Utility function to neatly construct an application URL
309 function _get_url( els ) {
310         return basepath + els.join('/');
311 }
312
313
314 $(document).ready( function() {
315         // See if we have the browser functionality we need
316         // TODO Also think of a test for SVG readiness
317         if( !!window.FileReader && !!window.File ) {
318                 $('#compatibility_check').empty();
319         }
320         
321     // call out to load the directory div
322     $('#textinfo_container').hide();
323     $('#textinfo_waitbox').hide();
324         refreshDirectory();
325         
326         // Set up the textinfo edit dialog
327         $('#textinfo-edit-dialog').dialog({
328                 autoOpen: false,
329                 height: 200,
330                 width: 300,
331                 modal: true,
332                 buttons: {
333                         Save: function (evt) {
334                                 $("#edit_textinfo_status").empty();
335                                 $(evt.target).button("disable");
336                                 var requrl = _get_url([ "textinfo", selectedTextID ]);
337                                 var reqparam = $('#edit_textinfo').serialize();
338                                 $.post( requrl, reqparam, function (data) {
339                                         // Reload the selected text fields
340                                         selectedTextInfo = data;
341                                         load_textinfo();
342                                         // Reenable the button and close the form
343                                         $(evt.target).button("enable");
344                                         $('#textinfo-edit-dialog').dialog('close');
345                                 }, 'json' );
346                         },
347                         Cancel: function() {
348                                 $('#textinfo-edit-dialog').dialog('close');
349                         }
350                 },
351                 open: function() {
352                         $("#edit_textinfo_status").empty();
353                         // Populate the form fields with the current values
354                         // edit_(name, language, public, owner)
355                         $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
356                                 var fname = '#edit_' + k;
357                                 // Special case: language Default is basically language null
358                                 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
359                                         $(fname).val( "" );
360                                 } else {
361                                         $(fname).val( selectedTextInfo[k] );
362                                 }
363                         });
364                         if( selectedTextInfo['public'] == true ) {
365                                 $('#edit_public').attr('checked','true');
366                         } else {
367                                 $('#edit_public').removeAttr('checked');
368                         }
369                 },
370         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
371                 $(event.target).parent().find('.ui-button').button("enable");
372         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 
373                 && ajaxSettings.type == 'POST' ) {
374                         display_error( jqXHR, $("#edit_textinfo_status") );
375         }
376         });
377
378         
379         // Set up the stemma editor dialog
380         $('#stemma-edit-dialog').dialog({
381                 autoOpen: false,
382                 height: 700,
383                 width: 600,
384                 modal: true,
385                 buttons: {
386                         Save: function (evt) {
387                                 $("#edit_stemma_status").empty();
388                                 $(evt.target).button("disable");
389                                 var stemmaseq = $('#stemmaseq').val();
390                                 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
391                                 var reqparam = { 'dot': $('#dot_field').val() };
392                                 // TODO We need to stash the literal SVG string in stemmata
393                                 // somehow. Implement accept header on server side to decide
394                                 // whether to send application/json or application/xml?
395                                 $.post( requrl, reqparam, function (data) {
396                                         // We received a stemma SVG string in return. 
397                                         // Update the current stemma sequence number
398                                         selectedStemmaID = data.stemmaid;
399                                         delete data.stemmaid;
400                                         // Stash the answer in the appropriate spot in our stemma array
401                                         stemmata[selectedStemmaID] = data;
402                                         // Display the new stemma
403                                         load_stemma( selectedStemmaID );
404                                         // Show the edit button, in case this was the first new stemma
405                                         $('#open_stemma_edit').show();
406                                         // Reenable the button and close the form
407                                         $(evt.target).button("enable");
408                                         $('#stemma-edit-dialog').dialog('close');
409                                 }, 'json' );
410                         },
411                         Cancel: function() {
412                                 $('#stemma-edit-dialog').dialog('close');
413                         }
414                 },
415                 open: function(evt) {
416                         $("#edit_stemma_status").empty();
417                         var stemmaseq = $('#stemmaseq').val();
418                         if( stemmaseq == 'n' ) {
419                                 // If we are creating a new stemma, populate the textarea with a
420                                 // bare digraph.
421                                 $(evt.target).dialog('option', 'title', 'Add a new stemma')
422                                 $('#dot_field').val( "digraph stemma {\n\n}" );
423                         } else {
424                                 // If we are editing a stemma, grab its stemmadot and populate the
425                                 // textarea with that.
426                                 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
427                                 $('#dot_field').val( 'Loading, please wait...' );
428                                 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
429                                 $.getJSON( doturl, function (data) {
430                                         // Re-insert the line breaks
431                                         var dotstring = data.dot.replace(/\|n/gm, "\n");                                        
432                                         $('#dot_field').val( dotstring );
433                                 });
434                         }
435                 },
436         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
437                 $(event.target).parent().find('.ui-button').button("enable");
438         if( ajaxSettings.url.indexOf( 'stemma' ) > -1 
439                 && ajaxSettings.type == 'POST' ) {
440                         display_error( jqXHR, $("#edit_stemma_status") );
441         }
442         });
443                 
444         $('#upload-collation-dialog').dialog({
445                 autoOpen: false,
446                 height: 360,
447                 width: 480,
448                 modal: true,
449                 buttons: {
450                   upload: {
451                     text: 'Upload',
452                     id: 'upload_button',
453                     click: function() {
454                             $('#upload_status').empty();
455                             $('#upload_button').button("disable");
456                 upload_new();
457             }
458                   },
459                   pick_file: {
460                     text: 'Pick File',
461                     id: 'pick_file_button',
462                     click: function() {
463                 $('#new_file').click();
464             }
465                   },
466                   Cancel: function() {
467                     $('#upload-collation-dialog').dialog('close');
468                   }
469                 },
470                 open: function() {
471                         // Set the upload button to its correct state based on
472                         // whether a file is loaded
473                         file_selected( $('#new_file').get(0) );
474                         $('#upload_status').empty();
475                 }
476         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
477                 // Reset button state
478                 file_selected( $('#new_file').get(0) );
479                 // Display error message if applicable
480         if( ajaxSettings.url.indexOf( 'newtradition' ) > -1 
481                 && ajaxSettings.type == 'POST' ) {
482                         display_error( jqXHR, $("#upload_status") );
483         }
484         });;
485         
486         $('#stemma_graph').mousedown( function(evt) {
487         evt.stopPropagation();
488         $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
489         $('body').mousemove( function(evt) {
490             mouse_scale = 1; // for now, was:  mouse_scale = svg_root_element.getScreenCTM().a;
491             dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
492             dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
493             $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
494             var svg_root = $('#stemma_graph svg').svg().svg('get').root();
495             var g = $('g.graph', svg_root).get(0);
496             current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
497             new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
498             g.setAttribute( 'transform', new_transform );
499             evt.returnValue = false;
500             evt.preventDefault();
501             return false;
502         });
503         $('body').mouseup( function(evt) {
504             $('body').unbind('mousemove');
505             $('body').unbind('mouseup');
506         });
507         });
508          
509         $('#stemma_graph').mousewheel(function (event, delta) {
510         event.returnValue = false;
511         event.preventDefault();
512         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
513         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
514         if( delta < -9 ) { delta = -9 }; 
515         var z = 1 + delta/10;
516         z = delta > 0 ? 1 : -1;
517         var svg_root = $('#stemma_graph svg').svg().svg('get').root();
518         var g = $('g.graph', svg_root).get(0);
519         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
520             var scaleLevel = z/10;
521             current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
522             new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
523             g.setAttribute( 'transform', new_transform );
524         }
525     });
526     
527 });