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