1 // Global state variables
4 var selectedStemmaID = -1;
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);
17 if( textOnLoad != "" ) {
18 // Call the click callback for the relevant text, if it is
20 $('#'+textOnLoad).click();
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") );
45 // Hide the functionality that is irrelevant
47 $('#open_stemma_add').show();
48 $('#open_stemma_edit').show();
49 $('#open_textinfo_edit').show();
51 $('#open_stemma_add').hide();
52 $('#open_stemma_edit').hide();
53 $('#open_textinfo_edit').hide();
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;
63 // Add the stemma(ta) and set up the stexaminer button
64 stemmata = textdata.stemmata;
65 if( stemmata.length ) {
67 $('#run_stexaminer').show();
69 selectedStemmaID = -1;
70 $('#open_stemma_edit').hide();
71 $('#run_stexaminer').hide();
73 load_stemma( selectedStemmaID );
74 // Set up the relationship mapper button
75 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
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 );
86 $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
87 $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
89 $('#owner_id').empty().append('no one');
90 if( selectedTextInfo.owner ) {
91 var owneremail = selectedTextInfo.owner;
92 var chop = owneremail.indexOf( '@' );
94 owneremail = owneremail.substr( 0, chop + 1 ) + '...';
96 $('#owner_id').empty().append( owneremail );
98 // Whether or not it is public
99 $('#not_public').empty();
100 if( selectedTextInfo['public'] == false ) {
101 $('#not_public').append('NOT ');
103 // What language setting it has, if any
104 $('#marked_language').empty().append('no language set');
105 if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
106 $('#marked_language').empty().append( selectedTextInfo.language );
110 // Enable / disable the appropriate buttons for paging through the stemma.
111 function show_stemmapager () {
112 $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
113 $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
114 if( selectedStemmaID > 0 ) {
115 $('.pager_left_button').click( function () {
116 load_stemma( selectedStemmaID - 1 );
117 }).removeClass( 'greyed_out' );
119 if( selectedStemmaID + 1 < stemmata.length ) {
120 $('.pager_right_button').click( function () {
121 load_stemma( selectedStemmaID + 1 );
122 }).removeClass( 'greyed_out' );
126 // Load a given stemma SVG into the stemmagraph box.
127 function load_stemma( idx ) {
128 // Load the stemma at idx
129 selectedStemmaID = idx;
132 loadSVG( stemmata[idx] );
133 // Stexaminer submit action
134 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
135 $('#run_stexaminer').attr( 'action', stexpath );
136 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
140 // Load the SVG we are given
141 function loadSVG(svgData) {
142 var svgElement = $('#stemma_graph');
144 $(svgElement).svg('destroy');
148 onLoad : function () {
149 var theSVG = svgElement.find('svg');
150 var svgoffset = theSVG.offset();
151 var browseroffset = 1;
152 // Firefox needs a different offset, stupidly enough
153 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
154 browseroffset = 3; // works for tall images
155 // ...but if the SVG is wider than it is tall, Firefox treats
156 // the top as being the top of the graph, loaded into the middle
157 // of the canvas, but then the margin at the top of the canvas
158 // extends upward. So we have to find the actual top of the canvas
159 // and correct for *that* instead.
160 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
161 if( vbdim.height < vbdim.width ) {
162 var vbscale = svgElement.width() / vbdim.width;
163 var vbrealheight = vbdim.height * vbscale;
164 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
167 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
168 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
173 // General-purpose error-handling function.
174 // TODO make sure this gets used throughout, where appropriate.
175 function display_error( jqXHR, el ) {
177 if( jqXHR.responseText == "" ) {
178 errmsg = "perhaps the server went down?"
182 errobj = jQuery.parseJSON( jqXHR.responseText );
183 errmsg = errobj.error;
184 } catch ( parse_err ) {
185 errmsg = "something went wrong on the server."
188 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
189 $(el).empty().append( msghtml ).show();
192 // Event to enable the upload button when a file has been selected
193 function file_selected( e ) {
194 if( e.files.length == 1 ) {
195 $('#upload_button').button('enable');
196 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
198 $('#upload_button').button('disable');
199 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
203 // Implement our own AJAX method that uses the features of XMLHttpRequest2
204 // but try to let it have a similar interface to jquery.post
205 // The data var needs to be a FormData() object.
206 // The callback will be given a single argument, which is the response data
207 // of the given type.
209 function post_xhr2( url, data, cb, type ) {
213 var xhr = new XMLHttpRequest();
214 // Set the expected response type
215 if( type === 'data' ) {
216 xhr.responseType = 'blob';
217 } else if( type === 'xml' ) {
218 xhr.responseType = 'document';
221 // Gin up an AJAX settings object
222 $.ajaxSetup({ url: url, type: 'POST' });
223 xhr.open( 'POST', url, true );
224 // Handle the results
225 xhr.onload = function( e ) {
226 // Get the response and parse it
227 // Call the callback with the response, whatever it was
229 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
231 if( type === 'json' ) {
232 resp = $.parseJSON( xhrs.responseText );
233 } else if ( type === 'xml' ) {
234 resp = xhrs.responseXML;
235 } else if ( type === 'text' ) {
236 resp = xhrs.responseText;
238 resp = xhrs.response;
242 // Trigger the ajaxError...
243 _trigger_ajaxerror( e );
246 xhr.onerror = _trigger_ajaxerror;
247 xhr.onabort = _trigger_ajaxerror;
251 function _trigger_ajaxerror( e ) {
253 var thrown = xhr.statusText || 'Request error';
254 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
257 function upload_new () {
258 // Serialize the upload form, get the file and attach it to the request,
259 // POST the lot and handle the response.
260 var newfile = $('#new_file').get(0).files[0];
261 var reader = new FileReader();
262 reader.onload = function( evt ) {
263 var data = new FormData();
264 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
265 data.append( o.name, o.value );
267 data.append( 'file', newfile );
268 var upload_url = _get_url([ 'newtradition' ]);
269 post_xhr2( upload_url, data, function( ret ) {
271 $('#upload-collation-dialog').dialog('close');
273 loadTradition( ret.id, ret.name, 1 );
274 } else if( ret.error ) {
275 $('#upload_status').empty().append(
276 $('<span>').attr('class', 'error').append( ret.error ) );
280 reader.onerror = function( evt ) {
281 var err_resp = 'File read error';
282 if( e.name == 'NotFoundError' ) {
283 err_resp = 'File not found';
284 } else if ( e.name == 'NotReadableError' ) {
285 err_resp == 'File unreadable - is it yours?';
286 } else if ( e.name == 'EncodingError' ) {
287 err_resp == 'File cannot be encoded - is it too long?';
288 } else if ( e.name == 'SecurityError' ) {
289 err_resp == 'File read security error';
291 // Fake a jqXHR object that we can pass to our generic error handler.
292 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
293 display_error( jqxhr, $('#upload_status') );
294 $('#upload_button').button('disable');
297 reader.readAsBinaryString( newfile );
300 // Utility function to neatly construct an application URL
301 function _get_url( els ) {
302 return basepath + els.join('/');
306 $(document).ready( function() {
307 // See if we have the browser functionality we need
308 // TODO Also think of a test for SVG readiness
309 if( !!window.FileReader && !!window.File ) {
310 $('#compatibility_check').empty();
313 // call out to load the directory div
314 $('#textinfo_container').hide();
315 $('#textinfo_waitbox').hide();
318 // Set up the textinfo edit dialog
319 $('#textinfo-edit-dialog').dialog({
325 Save: function (evt) {
326 $("#edit_textinfo_status").empty();
327 $(evt.target).button("disable");
328 var requrl = _get_url([ "textinfo", selectedTextID ]);
329 var reqparam = $('#edit_textinfo').serialize();
330 $.post( requrl, reqparam, function (data) {
331 // Reload the selected text fields
332 selectedTextInfo = data;
334 // Reenable the button and close the form
335 $(evt.target).button("enable");
336 $('#textinfo-edit-dialog').dialog('close');
340 $('#textinfo-edit-dialog').dialog('close');
344 $("#edit_textinfo_status").empty();
345 // Populate the form fields with the current values
346 // edit_(name, language, public, owner)
347 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
348 var fname = '#edit_' + k;
349 // Special case: language Default is basically language null
350 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
353 $(fname).val( selectedTextInfo[k] );
356 if( selectedTextInfo['public'] == true ) {
357 $('#edit_public').attr('checked','true');
359 $('#edit_public').removeAttr('checked');
362 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
363 $(event.target).parent().find('.ui-button').button("enable");
364 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
365 && ajaxSettings.type == 'POST' ) {
366 display_error( jqXHR, $("#edit_textinfo_status") );
371 // Set up the stemma editor dialog
372 $('#stemma-edit-dialog').dialog({
378 Save: function (evt) {
379 $("#edit_stemma_status").empty();
380 $(evt.target).button("disable");
381 var stemmaseq = $('#stemmaseq').val();
382 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
383 var reqparam = { 'dot': $('#dot_field').val() };
384 // TODO We need to stash the literal SVG string in stemmata
385 // somehow. Implement accept header on server side to decide
386 // whether to send application/json or application/xml?
387 $.post( requrl, reqparam, function (data) {
388 // We received a stemma SVG string in return.
389 // Update the current stemma sequence number
390 selectedStemmaID = data.stemmaid;
391 // Stash the answer in our SVG array
392 stemmata[selectedStemmaID] = data.stemmasvg;
393 // Display the new stemma
394 load_stemma( selectedStemmaID );
395 // Reenable the button and close the form
396 $(evt.target).button("enable");
397 $('#stemma-edit-dialog').dialog('close');
401 $('#stemma-edit-dialog').dialog('close');
404 open: function(evt) {
405 $("#edit_stemma_status").empty();
406 var stemmaseq = $('#stemmaseq').val();
407 if( stemmaseq == 'n' ) {
408 // If we are creating a new stemma, populate the textarea with a
410 $(evt.target).dialog('option', 'title', 'Add a new stemma')
411 $('#dot_field').val( "digraph stemma {\n\n}" );
413 // If we are editing a stemma, grab its stemmadot and populate the
414 // textarea with that.
415 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
416 $('#dot_field').val( 'Loading, please wait...' );
417 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
418 $.getJSON( doturl, function (data) {
419 // Re-insert the line breaks
420 var dotstring = data.dot.replace(/\|n/gm, "\n");
421 $('#dot_field').val( dotstring );
425 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
426 $(event.target).parent().find('.ui-button').button("enable");
427 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
428 && ajaxSettings.type == 'POST' ) {
429 display_error( jqXHR, $("#edit_stemma_status") );
433 $('#upload-collation-dialog').dialog({
443 $('#upload_status').empty();
444 $('#upload_button').button("disable");
450 id: 'pick_file_button',
452 $('#new_file').click();
456 $('#upload-collation-dialog').dialog('close');
460 // Set the upload button to its correct state based on
461 // whether a file is loaded
462 file_selected( $('#new_file').get(0) );
463 $('#upload_status').empty();
465 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
466 // Reset button state
467 file_selected( $('#new_file').get(0) );
468 // Display error message if applicable
469 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
470 && ajaxSettings.type == 'POST' ) {
471 display_error( jqXHR, $("#upload_status") );
475 $('#stemma_graph').mousedown( function(evt) {
476 evt.stopPropagation();
477 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
478 $('body').mousemove( function(evt) {
479 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
480 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
481 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
482 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
483 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
484 var g = $('g.graph', svg_root).get(0);
485 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
486 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
487 g.setAttribute( 'transform', new_transform );
488 evt.returnValue = false;
489 evt.preventDefault();
492 $('body').mouseup( function(evt) {
493 $('body').unbind('mousemove');
494 $('body').unbind('mouseup');
498 $('#stemma_graph').mousewheel(function (event, delta) {
499 event.returnValue = false;
500 event.preventDefault();
501 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
502 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
503 if( delta < -9 ) { delta = -9 };
504 var z = 1 + delta/10;
505 z = delta > 0 ? 1 : -1;
506 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
507 var g = $('g.graph', svg_root).get(0);
508 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
509 var scaleLevel = z/10;
510 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
511 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
512 g.setAttribute( 'transform', new_transform );