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