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_textinfo_edit').show();
49 $('#relatebutton_label').text('View collation and edit relationships');
51 $('#open_stemma_add').hide();
52 $('#open_textinfo_edit').hide();
53 $('#relatebutton_label').text('View collation and relationships');
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;
64 stemmata = textdata.stemmata;
65 if( stemmata.length ) {
68 selectedStemmaID = -1;
70 load_stemma( selectedStemmaID, editable );
71 // Set up the relationship mapper button
72 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
73 // Set up the download button
74 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
75 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
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 ( editable ) {
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, editable );
117 }).removeClass( 'greyed_out' );
119 if( selectedStemmaID + 1 < stemmata.length ) {
120 $('.pager_right_button').click( function () {
121 load_stemma( selectedStemmaID + 1, editable );
122 }).removeClass( 'greyed_out' );
126 // Load a given stemma SVG into the stemmagraph box.
127 function load_stemma( idx, editable ) {
128 // Load the stemma at idx
129 selectedStemmaID = idx;
130 show_stemmapager( editable );
131 $('#open_stemma_edit').hide();
132 $('#run_stexaminer').hide();
133 $('#stemma_identifier').empty();
135 // Load the stemma and its properties
136 var stemmadata = stemmata[idx];
138 $('#open_stemma_edit').show();
140 if( stemmadata.directed ) {
141 // Stexaminer submit action
142 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
143 $('#run_stexaminer').attr( 'action', stexpath );
144 $('#run_stexaminer').show();
146 loadSVG( stemmadata.svg );
147 $('#stemma_identifier').text( stemmadata.name );
148 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
152 // Load the SVG we are given
153 function loadSVG(svgData) {
154 var svgElement = $('#stemma_graph');
156 $(svgElement).svg('destroy');
160 onLoad : function () {
161 var theSVG = svgElement.find('svg');
162 var svgoffset = theSVG.offset();
163 var browseroffset = 1;
164 // Firefox needs a different offset, stupidly enough
165 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
166 browseroffset = 3; // works for tall images
167 // ...but if the SVG is wider than it is tall, Firefox treats
168 // the top as being the top of the graph, loaded into the middle
169 // of the canvas, but then the margin at the top of the canvas
170 // extends upward. So we have to find the actual top of the canvas
171 // and correct for *that* instead.
172 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
173 if( vbdim.height < vbdim.width ) {
174 var vbscale = svgElement.width() / vbdim.width;
175 var vbrealheight = vbdim.height * vbscale;
176 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
179 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
180 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
185 // General-purpose error-handling function.
186 // TODO make sure this gets used throughout, where appropriate.
187 function display_error( jqXHR, el ) {
189 if( jqXHR.responseText == "" ) {
190 errmsg = "perhaps the server went down?"
194 errobj = jQuery.parseJSON( jqXHR.responseText );
195 errmsg = errobj.error;
196 } catch ( parse_err ) {
197 errmsg = "something went wrong on the server."
200 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
201 $(el).empty().append( msghtml ).show();
204 // Event to enable the upload button when a file has been selected
205 function file_selected( e ) {
206 if( e.files.length == 1 ) {
207 $('#upload_button').button('enable');
208 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
210 $('#upload_button').button('disable');
211 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
215 // Implement our own AJAX method that uses the features of XMLHttpRequest2
216 // but try to let it have a similar interface to jquery.post
217 // The data var needs to be a FormData() object.
218 // The callback will be given a single argument, which is the response data
219 // of the given type.
221 function post_xhr2( url, data, cb, type ) {
225 var xhr = new XMLHttpRequest();
226 // Set the expected response type
227 if( type === 'data' ) {
228 xhr.responseType = 'blob';
229 } else if( type === 'xml' ) {
230 xhr.responseType = 'document';
233 // Gin up an AJAX settings object
234 $.ajaxSetup({ url: url, type: 'POST' });
235 xhr.open( 'POST', url, true );
236 // Handle the results
237 xhr.onload = function( e ) {
238 // Get the response and parse it
239 // Call the callback with the response, whatever it was
241 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
243 if( type === 'json' ) {
244 resp = $.parseJSON( xhrs.responseText );
245 } else if ( type === 'xml' ) {
246 resp = xhrs.responseXML;
247 } else if ( type === 'text' ) {
248 resp = xhrs.responseText;
250 resp = xhrs.response;
254 // Trigger the ajaxError...
255 _trigger_ajaxerror( e );
258 xhr.onerror = _trigger_ajaxerror;
259 xhr.onabort = _trigger_ajaxerror;
263 function _trigger_ajaxerror( e ) {
265 var thrown = xhr.statusText || 'Request error';
266 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
269 function upload_new () {
270 // Serialize the upload form, get the file and attach it to the request,
271 // POST the lot and handle the response.
272 var newfile = $('#new_file').get(0).files[0];
273 var reader = new FileReader();
274 reader.onload = function( evt ) {
275 var data = new FormData();
276 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
277 data.append( o.name, o.value );
279 data.append( 'file', newfile );
280 var upload_url = _get_url([ 'newtradition' ]);
281 post_xhr2( upload_url, data, function( ret ) {
283 $('#upload-collation-dialog').dialog('close');
285 loadTradition( ret.id, ret.name, 1 );
286 } else if( ret.error ) {
287 $('#upload_status').empty().append(
288 $('<span>').attr('class', 'error').append( ret.error ) );
292 reader.onerror = function( evt ) {
293 var err_resp = 'File read error';
294 if( e.name == 'NotFoundError' ) {
295 err_resp = 'File not found';
296 } else if ( e.name == 'NotReadableError' ) {
297 err_resp == 'File unreadable - is it yours?';
298 } else if ( e.name == 'EncodingError' ) {
299 err_resp == 'File cannot be encoded - is it too long?';
300 } else if ( e.name == 'SecurityError' ) {
301 err_resp == 'File read security error';
303 // Fake a jqXHR object that we can pass to our generic error handler.
304 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
305 display_error( jqxhr, $('#upload_status') );
306 $('#upload_button').button('disable');
309 reader.readAsBinaryString( newfile );
312 // Utility function to neatly construct an application URL
313 function _get_url( els ) {
314 return basepath + els.join('/');
318 $(document).ready( function() {
319 // See if we have the browser functionality we need
320 // TODO Also think of a test for SVG readiness
321 if( !!window.FileReader && !!window.File ) {
322 $('#compatibility_check').empty();
325 // call out to load the directory div
326 $('#textinfo_container').hide();
327 $('#textinfo_waitbox').hide();
330 // Set up the textinfo edit dialog
331 $('#textinfo-edit-dialog').dialog({
337 Save: function (evt) {
338 $("#edit_textinfo_status").empty();
339 $(evt.target).button("disable");
340 var requrl = _get_url([ "textinfo", selectedTextID ]);
341 var reqparam = $('#edit_textinfo').serialize();
342 $.post( requrl, reqparam, function (data) {
343 // Reload the selected text fields
344 selectedTextInfo = data;
346 // Reenable the button and close the form
347 $(evt.target).button("enable");
348 $('#textinfo-edit-dialog').dialog('close');
352 $('#textinfo-edit-dialog').dialog('close');
356 $("#edit_textinfo_status").empty();
357 // Populate the form fields with the current values
358 // edit_(name, language, public, owner)
359 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
360 var fname = '#edit_' + k;
361 // Special case: language Default is basically language null
362 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
365 $(fname).val( selectedTextInfo[k] );
368 if( selectedTextInfo['public'] == true ) {
369 $('#edit_public').attr('checked','true');
371 $('#edit_public').removeAttr('checked');
374 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
375 $(event.target).parent().find('.ui-button').button("enable");
376 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
377 && ajaxSettings.type == 'POST' ) {
378 display_error( jqXHR, $("#edit_textinfo_status") );
383 // Set up the stemma editor dialog
384 $('#stemma-edit-dialog').dialog({
390 Save: function (evt) {
391 $("#edit_stemma_status").empty();
392 $(evt.target).button("disable");
393 var stemmaseq = $('#stemmaseq').val();
394 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
395 var reqparam = { 'dot': $('#dot_field').val() };
396 // TODO We need to stash the literal SVG string in stemmata
397 // somehow. Implement accept header on server side to decide
398 // whether to send application/json or application/xml?
399 $.post( requrl, reqparam, function (data) {
400 // We received a stemma SVG string in return.
401 // Update the current stemma sequence number
402 selectedStemmaID = data.stemmaid;
403 delete data.stemmaid;
404 // Stash the answer in the appropriate spot in our stemma array
405 stemmata[selectedStemmaID] = data;
406 // Display the new stemma
407 load_stemma( selectedStemmaID, true );
408 // Reenable the button and close the form
409 $(evt.target).button("enable");
410 $('#stemma-edit-dialog').dialog('close');
414 $('#stemma-edit-dialog').dialog('close');
417 open: function(evt) {
418 $("#edit_stemma_status").empty();
419 var stemmaseq = $('#stemmaseq').val();
420 if( stemmaseq == 'n' ) {
421 // If we are creating a new stemma, populate the textarea with a
423 $(evt.target).dialog('option', 'title', 'Add a new stemma')
424 $('#dot_field').val( "digraph stemma {\n\n}" );
426 // If we are editing a stemma, grab its stemmadot and populate the
427 // textarea with that.
428 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
429 $('#dot_field').val( 'Loading, please wait...' );
430 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
431 $.getJSON( doturl, function (data) {
432 // Re-insert the line breaks
433 var dotstring = data.dot.replace(/\|n/gm, "\n");
434 $('#dot_field').val( dotstring );
438 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
439 $(event.target).parent().find('.ui-button').button("enable");
440 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
441 && ajaxSettings.type == 'POST' ) {
442 display_error( jqXHR, $("#edit_stemma_status") );
446 $('#upload-collation-dialog').dialog({
456 $('#upload_status').empty();
457 $('#upload_button').button("disable");
463 id: 'pick_file_button',
465 $('#new_file').click();
469 $('#upload-collation-dialog').dialog('close');
473 // Set the upload button to its correct state based on
474 // whether a file is loaded
475 file_selected( $('#new_file').get(0) );
476 $('#upload_status').empty();
478 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
479 // Reset button state
480 file_selected( $('#new_file').get(0) );
481 // Display error message if applicable
482 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
483 && ajaxSettings.type == 'POST' ) {
484 display_error( jqXHR, $("#upload_status") );
488 $('#stemma_graph').mousedown( function(evt) {
489 evt.stopPropagation();
490 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
491 $('body').mousemove( function(evt) {
492 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
493 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
494 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
495 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
496 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
497 var g = $('g.graph', svg_root).get(0);
498 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
499 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
500 g.setAttribute( 'transform', new_transform );
501 evt.returnValue = false;
502 evt.preventDefault();
505 $('body').mouseup( function(evt) {
506 $('body').unbind('mousemove');
507 $('body').unbind('mouseup');
511 $('#stemma_graph').mousewheel(function (event, delta) {
512 event.returnValue = false;
513 event.preventDefault();
514 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
515 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
516 if( delta < -9 ) { delta = -9 };
517 var z = 1 + delta/10;
518 z = delta > 0 ? 1 : -1;
519 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
520 var g = $('g.graph', svg_root).get(0);
521 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
522 var scaleLevel = z/10;
523 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
524 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
525 g.setAttribute( 'transform', new_transform );