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_stemweb_ui').show();
49 $('#open_textinfo_edit').show();
50 $('#relatebutton_label').text('View collation and edit relationships');
52 $('#open_stemma_add').hide();
53 $('#open_stemweb_ui').hide();
54 $('#open_textinfo_edit').hide();
55 $('#relatebutton_label').text('View collation and relationships');
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;
66 stemmata = textdata.stemmata;
67 if( stemmata.length ) {
70 selectedStemmaID = -1;
72 load_stemma( selectedStemmaID, editable );
73 // Set up the relationship mapper button
74 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
75 // Set up the download button
76 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
77 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
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 );
88 $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
89 $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
91 $('#owner_id').empty().append('no one');
92 if( selectedTextInfo.owner ) {
93 var owneremail = selectedTextInfo.owner;
94 var chop = owneremail.indexOf( '@' );
96 owneremail = owneremail.substr( 0, chop + 1 ) + '...';
98 $('#owner_id').empty().append( owneremail );
100 // Whether or not it is public
101 $('#not_public').empty();
102 if( selectedTextInfo['public'] == false ) {
103 $('#not_public').append('NOT ');
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 );
112 // Enable / disable the appropriate buttons for paging through the stemma.
113 function show_stemmapager ( editable ) {
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, editable );
119 }).removeClass( 'greyed_out' );
121 if( selectedStemmaID + 1 < stemmata.length ) {
122 $('.pager_right_button').click( function () {
123 load_stemma( selectedStemmaID + 1, editable );
124 }).removeClass( 'greyed_out' );
128 // Load a given stemma SVG into the stemmagraph box.
129 function load_stemma( idx, editable ) {
130 // Load the stemma at idx
131 selectedStemmaID = idx;
132 show_stemmapager( editable );
133 $('#open_stemma_edit').hide();
134 $('#run_stexaminer').hide();
135 $('#stemma_identifier').empty();
137 // Load the stemma and its properties
138 var stemmadata = stemmata[idx];
140 $('#open_stemma_edit').show();
142 if( stemmadata.directed ) {
143 // Stexaminer submit action
144 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
145 $('#run_stexaminer').attr( 'action', stexpath );
146 $('#run_stexaminer').show();
148 loadSVG( stemmadata.svg );
149 $('#stemma_identifier').text( stemmadata.name );
150 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
154 // Load the SVG we are given
155 function loadSVG(svgData) {
156 var svgElement = $('#stemma_graph');
158 $(svgElement).svg('destroy');
162 onLoad : function () {
163 var theSVG = svgElement.find('svg');
164 var svgoffset = theSVG.offset();
165 var browseroffset = 1;
166 // Firefox needs a different offset, stupidly enough
167 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
168 browseroffset = 3; // works for tall images
169 // ...but if the SVG is wider than it is tall, Firefox treats
170 // the top as being the top of the graph, loaded into the middle
171 // of the canvas, but then the margin at the top of the canvas
172 // extends upward. So we have to find the actual top of the canvas
173 // and correct for *that* instead.
174 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
175 if( vbdim.height < vbdim.width ) {
176 var vbscale = svgElement.width() / vbdim.width;
177 var vbrealheight = vbdim.height * vbscale;
178 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
181 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
182 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
187 // General-purpose error-handling function.
188 // TODO make sure this gets used throughout, where appropriate.
189 function display_error( jqXHR, el ) {
191 if( jqXHR.responseText == "" ) {
192 errmsg = "perhaps the server went down?"
196 errobj = jQuery.parseJSON( jqXHR.responseText );
197 errmsg = errobj.error;
198 } catch ( parse_err ) {
199 errmsg = "something went wrong on the server."
202 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
203 $(el).empty().append( msghtml ).show();
206 // Event to enable the upload button when a file has been selected
207 function file_selected( e ) {
208 if( e.files.length == 1 ) {
209 $('#upload_button').button('enable');
210 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
212 $('#upload_button').button('disable');
213 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
217 // Implement our own AJAX method that uses the features of XMLHttpRequest2
218 // but try to let it have a similar interface to jquery.post
219 // The data var needs to be a FormData() object.
220 // The callback will be given a single argument, which is the response data
221 // of the given type.
223 function post_xhr2( url, data, cb, type ) {
227 var xhr = new XMLHttpRequest();
228 // Set the expected response type
229 if( type === 'data' ) {
230 xhr.responseType = 'blob';
231 } else if( type === 'xml' ) {
232 xhr.responseType = 'document';
235 // Gin up an AJAX settings object
236 $.ajaxSetup({ url: url, type: 'POST' });
237 xhr.open( 'POST', url, true );
238 // Handle the results
239 xhr.onload = function( e ) {
240 // Get the response and parse it
241 // Call the callback with the response, whatever it was
243 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
245 if( type === 'json' ) {
246 resp = $.parseJSON( xhrs.responseText );
247 } else if ( type === 'xml' ) {
248 resp = xhrs.responseXML;
249 } else if ( type === 'text' ) {
250 resp = xhrs.responseText;
252 resp = xhrs.response;
256 // Trigger the ajaxError...
257 _trigger_ajaxerror( e );
260 xhr.onerror = _trigger_ajaxerror;
261 xhr.onabort = _trigger_ajaxerror;
265 function _trigger_ajaxerror( e ) {
267 var thrown = xhr.statusText || 'Request error';
268 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
271 function upload_new () {
272 // Serialize the upload form, get the file and attach it to the request,
273 // POST the lot and handle the response.
274 var newfile = $('#new_file').get(0).files[0];
275 var reader = new FileReader();
276 reader.onload = function( evt ) {
277 var data = new FormData();
278 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
279 data.append( o.name, o.value );
281 data.append( 'file', newfile );
282 var upload_url = _get_url([ 'newtradition' ]);
283 post_xhr2( upload_url, data, function( ret ) {
285 $('#upload-collation-dialog').dialog('close');
287 loadTradition( ret.id, ret.name, 1 );
288 } else if( ret.error ) {
289 $('#upload_status').empty().append(
290 $('<span>').attr('class', 'error').append( ret.error ) );
294 reader.onerror = function( evt ) {
295 var err_resp = 'File read error';
296 if( e.name == 'NotFoundError' ) {
297 err_resp = 'File not found';
298 } else if ( e.name == 'NotReadableError' ) {
299 err_resp == 'File unreadable - is it yours?';
300 } else if ( e.name == 'EncodingError' ) {
301 err_resp == 'File cannot be encoded - is it too long?';
302 } else if ( e.name == 'SecurityError' ) {
303 err_resp == 'File read security error';
305 // Fake a jqXHR object that we can pass to our generic error handler.
306 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
307 display_error( jqxhr, $('#upload_status') );
308 $('#upload_button').button('disable');
311 reader.readAsBinaryString( newfile );
314 // Utility function to neatly construct an application URL
315 function _get_url( els ) {
316 return basepath + els.join('/');
320 $(document).ready( function() {
321 // See if we have the browser functionality we need
322 // TODO Also think of a test for SVG readiness
323 if( !!window.FileReader && !!window.File ) {
324 $('#compatibility_check').empty();
327 // call out to load the directory div
328 $('#textinfo_container').hide();
329 $('#textinfo_waitbox').hide();
332 // Set up the textinfo edit dialog
333 $('#textinfo-edit-dialog').dialog({
339 Save: function (evt) {
340 $("#edit_textinfo_status").empty();
341 $(evt.target).button("disable");
342 var requrl = _get_url([ "textinfo", selectedTextID ]);
343 var reqparam = $('#edit_textinfo').serialize();
344 $.post( requrl, reqparam, function (data) {
345 // Reload the selected text fields
346 selectedTextInfo = data;
348 // Reenable the button and close the form
349 $(evt.target).button("enable");
350 $('#textinfo-edit-dialog').dialog('close');
354 $('#textinfo-edit-dialog').dialog('close');
358 $("#edit_textinfo_status").empty();
359 // Populate the form fields with the current values
360 // edit_(name, language, public, owner)
361 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
362 var fname = '#edit_' + k;
363 // Special case: language Default is basically language null
364 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
367 $(fname).val( selectedTextInfo[k] );
370 if( selectedTextInfo['public'] == true ) {
371 $('#edit_public').attr('checked','true');
373 $('#edit_public').removeAttr('checked');
376 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
377 $(event.target).parent().find('.ui-button').button("enable");
378 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
379 && ajaxSettings.type == 'POST' ) {
380 display_error( jqXHR, $("#edit_textinfo_status") );
385 // Set up the stemma editor dialog
386 $('#stemma-edit-dialog').dialog({
392 Save: function (evt) {
393 $("#edit_stemma_status").empty();
394 $(evt.target).button("disable");
395 var stemmaseq = $('#stemmaseq').val();
396 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
397 var reqparam = { 'dot': $('#dot_field').val() };
398 // TODO We need to stash the literal SVG string in stemmata
399 // somehow. Implement accept header on server side to decide
400 // whether to send application/json or application/xml?
401 $.post( requrl, reqparam, function (data) {
402 // We received a stemma SVG string in return.
403 // Update the current stemma sequence number
404 selectedStemmaID = data.stemmaid;
405 delete data.stemmaid;
406 // Stash the answer in the appropriate spot in our stemma array
407 stemmata[selectedStemmaID] = data;
408 // Display the new stemma
409 load_stemma( selectedStemmaID, true );
410 // Reenable the button and close the form
411 $(evt.target).button("enable");
412 $('#stemma-edit-dialog').dialog('close');
416 $('#stemma-edit-dialog').dialog('close');
419 open: function(evt) {
420 $("#edit_stemma_status").empty();
421 var stemmaseq = $('#stemmaseq').val();
422 if( stemmaseq == 'n' ) {
423 // If we are creating a new stemma, populate the textarea with a
425 $(evt.target).dialog('option', 'title', 'Add a new stemma')
426 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
428 // If we are editing a stemma, grab its stemmadot and populate the
429 // textarea with that.
430 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
431 $('#dot_field').val( 'Loading, please wait...' );
432 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
433 $.getJSON( doturl, function (data) {
434 // Re-insert the line breaks
435 var dotstring = data.dot.replace(/\|n/gm, "\n");
436 $('#dot_field').val( dotstring );
440 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
441 $(event.target).parent().find('.ui-button').button("enable");
442 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
443 && ajaxSettings.type == 'POST' ) {
444 display_error( jqXHR, $("#edit_stemma_status") );
448 $('#stemweb-ui-dialog').dialog({
454 Run: function (evt) {
455 $("#stemweb_run_status").empty();
456 $(evt.target).button("disable");
457 var requrl = _get_url([ "stemweb", "request" ]);
458 var reqparam = $('#call_stemweb').serialize();
459 // TODO We need to stash the literal SVG string in stemmata
460 // somehow. Implement accept header on server side to decide
461 // whether to send application/json or application/xml?
462 $.getJSON( requrl, reqparam, function (data) {
463 // Job ID is in data.jobid. TODO do something with it.
464 $(evt.target).button("enable");
465 $('#stemma-edit-dialog').dialog('close');
469 $('#stemweb-ui-dialog').dialog('close');
472 create: function(evt) {
473 // Call out to Stemweb to get the algorithm options, with which we
474 // populate the form.
475 var algorithmTypes = {};
476 var algorithmArgs = {};
477 $.each( stemwebAlgorithms, function( i, o ) {
478 if( o.model === 'algorithms.algorithm' ) {
479 // it's an algorithm.
480 algorithmTypes[ o.pk ] = o.fields;
481 } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
482 // it's an option for an algorithm that we should display.
483 algorithmArgs[ o.pk ] = o.fields;
486 $.each( algorithmTypes, function( pk, fields ) {
487 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
488 $('#stemweb_algorithm').append( algopt );
490 // Set up the relevant options for whichever algorithm is chosen.
491 // "key" -> form name, option ID "stemweb_$key_opt"
492 // "name" -> form label
493 $('#stemweb_algorithm').change( function() {
494 var pk = $(this).val();
495 $('#stemweb_runtime_options').empty();
496 $.each( algorithmTypes[pk].args, function( i, apk ) {
497 var argInfo = algorithmArgs[apk];
499 // Make the element ID
500 var optId = 'stemweb_' + argInfo.key + '_opt';
502 var optLabel = $('<label>').attr( 'for', optId )
503 .append( argInfo.name + ": " );
505 var argType = argInfo.value;
506 if( argType === 'positive_integer' ) {
507 // Make it an input field of smallish size.
508 optCtrl = $('<input>').attr( 'size', 4 );
509 } else if ( argType === 'boolean' ) {
510 // Make it a checkbox.
511 optCtrl = $('<checkbox>');
513 // Add the name and element ID
514 optCtrl.attr( 'name', argInfo.name ).attr( 'id', optId );
515 // Append the label and the option itself to the form.
516 $('#stemweb_runtime_options').append( optLabel )
517 .append( optCtrl ).append( $('<br>') );
521 // Prime the initial options
522 $('#stemweb_algorithm').change();
524 open: function(evt) {
525 $('#stemweb_run_status').empty();
526 $('#stemweb_tradition').attr('value', selectedTextID );
528 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
529 $(event.target).parent().find('.ui-button').button("enable");
530 if( ajaxSettings.url.indexOf( 'algorithms' ) > -1
531 && ajaxSettings.type == 'POST' ) {
532 display_error( jqXHR, $("#stemweb_run_status") );
536 $('#upload-collation-dialog').dialog({
546 $('#upload_status').empty();
547 $('#upload_button').button("disable");
553 id: 'pick_file_button',
555 $('#new_file').click();
559 $('#upload-collation-dialog').dialog('close');
563 // Set the upload button to its correct state based on
564 // whether a file is loaded
565 file_selected( $('#new_file').get(0) );
566 $('#upload_status').empty();
568 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
569 // Reset button state
570 file_selected( $('#new_file').get(0) );
571 // Display error message if applicable
572 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
573 && ajaxSettings.type == 'POST' ) {
574 display_error( jqXHR, $("#upload_status") );
578 $('#stemma_graph').mousedown( function(evt) {
579 evt.stopPropagation();
580 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
581 $('body').mousemove( function(evt) {
582 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
583 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
584 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
585 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
586 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
587 var g = $('g.graph', svg_root).get(0);
588 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
589 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
590 g.setAttribute( 'transform', new_transform );
591 evt.returnValue = false;
592 evt.preventDefault();
595 $('body').mouseup( function(evt) {
596 $('body').unbind('mousemove');
597 $('body').unbind('mouseup');
601 $('#stemma_graph').mousewheel(function (event, delta) {
602 event.returnValue = false;
603 event.preventDefault();
604 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
605 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
606 if( delta < -9 ) { delta = -9 };
607 var z = 1 + delta/10;
608 z = delta > 0 ? 1 : -1;
609 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
610 var g = $('g.graph', svg_root).get(0);
611 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
612 var scaleLevel = z/10;
613 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
614 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
615 g.setAttribute( 'transform', new_transform );