1cbc2ac05f3da3694352e19da1ec77e2e5fdb82d
[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         // See if we have the browser functionality we need
247         // TODO Also think of a test for SVG readiness
248         if( typeof window.FileReader && typeof window.File ) {
249                 $('#compatibility_check').empty();
250         }
251         
252     // call out to load the directory div
253     $('#textinfo_container').hide();
254     $('#textinfo_waitbox').hide();
255         refreshDirectory();
256         
257         // Set up the textinfo edit dialog
258         $('#textinfo-edit-dialog').dialog({
259                 autoOpen: false,
260                 height: 200,
261                 width: 300,
262                 modal: true,
263                 buttons: {
264                         Save: function (evt) {
265                                 $("#edit_textinfo_status").empty();
266                                 $(evt.target).button("disable");
267                                 var requrl = _get_url([ "textinfo", selectedTextID ]);
268                                 var reqparam = $('#edit_textinfo').serialize();
269                                 $.post( requrl, reqparam, function (data) {
270                                         // Reload the selected text fields
271                                         selectedTextInfo = data;
272                                         load_textinfo();
273                                         // Reenable the button and close the form
274                                         $(evt.target).button("enable");
275                                         $('#textinfo-edit-dialog').dialog('close');
276                                 }, 'json' );
277                         },
278                         Cancel: function() {
279                                 $('#textinfo-edit-dialog').dialog('close');
280                         }
281                 },
282                 open: function() {
283                         $("#edit_textinfo_status").empty();
284                         // Populate the form fields with the current values
285                         // edit_(name, language, public, owner)
286                         $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
287                                 var fname = '#edit_' + k;
288                                 // Special case: language Default is basically language null
289                                 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
290                                         $(fname).val( "" );
291                                 } else {
292                                         $(fname).val( selectedTextInfo[k] );
293                                 }
294                         });
295                         if( selectedTextInfo['public'] == true ) {
296                                 $('#edit_public').attr('checked','true');
297                         } else {
298                                 $('#edit_public').removeAttr('checked');
299                         }
300                 },
301         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
302                 $(event.target).parent().find('.ui-button').button("enable");
303         if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 
304                 && ajaxSettings.type == 'POST' ) {
305                         display_error( jqXHR, $("#edit_textinfo_status") );
306         }
307         });
308
309         
310         // Set up the stemma editor dialog
311         $('#stemma-edit-dialog').dialog({
312                 autoOpen: false,
313                 height: 700,
314                 width: 600,
315                 modal: true,
316                 buttons: {
317                         Save: function (evt) {
318                                 $("#edit_stemma_status").empty();
319                                 $(evt.target).button("disable");
320                                 var stemmaseq = $('#stemmaseq').val();
321                                 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
322                                 var reqparam = { 'dot': $('#dot_field').val() };
323                                 // TODO We need to stash the literal SVG string in stemmata
324                                 // somehow. Implement accept header on server side to decide
325                                 // whether to send application/json or application/xml?
326                                 $.post( requrl, reqparam, function (data) {
327                                         // We received a stemma SVG string in return. 
328                                         // Update the current stemma sequence number
329                                         selectedStemmaID = data.stemmaid;
330                                         // Stash the answer in our SVG array
331                                         stemmata[selectedStemmaID] = data.stemmasvg;
332                                         // Display the new stemma
333                                         load_stemma( selectedStemmaID );
334                                         // Reenable the button and close the form
335                                         $(evt.target).button("enable");
336                                         $('#stemma-edit-dialog').dialog('close');
337                                 }, 'json' );
338                         },
339                         Cancel: function() {
340                                 $('#stemma-edit-dialog').dialog('close');
341                         }
342                 },
343                 open: function(evt) {
344                         $("#edit_stemma_status").empty();
345                         var stemmaseq = $('#stemmaseq').val();
346                         if( stemmaseq == 'n' ) {
347                                 // If we are creating a new stemma, populate the textarea with a
348                                 // bare digraph.
349                                 $(evt.target).dialog('option', 'title', 'Add a new stemma')
350                                 $('#dot_field').val( "digraph stemma {\n\n}" );
351                         } else {
352                                 // If we are editing a stemma, grab its stemmadot and populate the
353                                 // textarea with that.
354                                 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
355                                 $('#dot_field').val( 'Loading, please wait...' );
356                                 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
357                                 $.getJSON( doturl, function (data) {
358                                         // Re-insert the line breaks
359                                         var dotstring = data.dot.replace(/\|n/gm, "\n");                                        
360                                         $('#dot_field').val( dotstring );
361                                 });
362                         }
363                 },
364         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
365                 $(event.target).parent().find('.ui-button').button("enable");
366         if( ajaxSettings.url.indexOf( 'stemma' ) > -1 
367                 && ajaxSettings.type == 'POST' ) {
368                         display_error( jqXHR, $("#edit_stemma_status") );
369         }
370         });
371                 
372         $('#upload-collation-dialog').dialog({
373                 autoOpen: false,
374                 height: 360,
375                 width: 480,
376                 modal: true,
377                 buttons: {
378                   upload: {
379                     text: 'Upload',
380                     id: 'upload_button',
381                     click: function() {
382                             $('#upload_status').empty();
383                             $('#upload_button').button("disable");
384                 upload_new();
385             }
386                   },
387                   Cancel: function() {
388                     $('#upload-collation-dialog').dialog('close');
389                   }
390                 },
391                 open: function() {
392                         // Set the upload button to its correct state based on
393                         // whether a file is loaded
394                         file_selected( $('#new_file').get(0) );
395                 }
396         }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
397                 // Reset button state
398                 file_selected( $('#new_file').get(0) );
399                 // Display error message if applicable
400         if( ajaxSettings.url.indexOf( 'newtradition' ) > -1 
401                 && ajaxSettings.type == 'POST' ) {
402                         display_error( jqXHR, $("#upload_status") );
403         }
404         });;
405         
406         $('#stemma_graph').mousedown( function(evt) {
407         evt.stopPropagation();
408         $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
409         $('body').mousemove( function(evt) {
410             mouse_scale = 1; // for now, was:  mouse_scale = svg_root_element.getScreenCTM().a;
411             dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
412             dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
413             $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
414             var svg_root = $('#stemma_graph svg').svg().svg('get').root();
415             var g = $('g.graph', svg_root).get(0);
416             current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
417             new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
418             g.setAttribute( 'transform', new_transform );
419             evt.returnValue = false;
420             evt.preventDefault();
421             return false;
422         });
423         $('body').mouseup( function(evt) {
424             $('body').unbind('mousemove');
425             $('body').unbind('mouseup');
426         });
427         });
428          
429         $('#stemma_graph').mousewheel(function (event, delta) {
430         event.returnValue = false;
431         event.preventDefault();
432         if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
433         if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
434         if( delta < -9 ) { delta = -9 }; 
435         var z = 1 + delta/10;
436         z = delta > 0 ? 1 : -1;
437         var svg_root = $('#stemma_graph svg').svg().svg('get').root();
438         var g = $('g.graph', svg_root).get(0);
439         if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
440             var scaleLevel = z/10;
441             current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
442             new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
443             g.setAttribute( 'transform', new_transform );
444         }
445     });
446     
447 });