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_stemweb_ui').hide();
53 $('#query_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();
136 // Add the relevant Stemweb functionality
138 if( selectedTextInfo.stemweb_jobid == 0 ) {
139 $('#open_stemweb_ui').show();
140 $('#query_stemweb_ui').hide();
142 $('#query_stemweb_ui').show();
143 $('#open_stemweb_ui').hide();
147 // Load the stemma and its properties
148 var stemmadata = stemmata[idx];
150 $('#open_stemma_edit').show();
152 if( stemmadata.directed ) {
153 // Stexaminer submit action
154 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
155 $('#run_stexaminer').attr( 'action', stexpath );
156 $('#run_stexaminer').show();
158 loadSVG( stemmadata.svg );
159 $('#stemma_identifier').text( stemmadata.name );
160 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
164 function query_stemweb_progress() {
165 var requrl = _get_url([ "stemweb", "query", selectedTextInfo.stemweb_jobid ]);
166 $.getJSON( requrl, function (data) {
167 // Look for a status message, either success, running, or notfound.
168 if( data.status === 'success' ) {
169 // Add the new stemmata to the textinfo and tell the user.
170 selectedTextInfo.stemweb_jobid = 0;
171 if( data.stemmata.length > 0 ) {
172 stemmata = stemmata.concat( data.stemmata );
173 if( selectedStemmaID == -1 ) {
174 // We have a stemma for the first time; load the first one.
175 load_stemma( 0, true );
177 // Move to the index of the first added stemma.
178 var newIdx = stemmata.length - data.stemmata.length;
179 load_stemma( newIdx, true );
181 alert( 'You have one or more new stemmata!' );
183 alert( 'Stemweb run finished with no stemmata...huh?!' );
185 } else if( data.status === 'running' ) {
186 // Just tell the user.
187 alert( 'Your Stemweb query is still running!' );
188 } else if( data.status === 'notfound' ) {
189 // Ask the user to refresh, for now.
190 alert( 'Your Stemweb query probably finished and reported back. Please reload to check.' );
195 // Load the SVG we are given
196 function loadSVG(svgData) {
197 var svgElement = $('#stemma_graph');
199 $(svgElement).svg('destroy');
203 onLoad : function () {
204 var theSVG = svgElement.find('svg');
205 var svgoffset = theSVG.offset();
206 var browseroffset = 1;
207 // Firefox needs a different offset, stupidly enough
208 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
209 browseroffset = 3; // works for tall images
210 // ...but if the SVG is wider than it is tall, Firefox treats
211 // the top as being the top of the graph, loaded into the middle
212 // of the canvas, but then the margin at the top of the canvas
213 // extends upward. So we have to find the actual top of the canvas
214 // and correct for *that* instead.
215 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
216 if( vbdim.height < vbdim.width ) {
217 var vbscale = svgElement.width() / vbdim.width;
218 var vbrealheight = vbdim.height * vbscale;
219 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
222 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
223 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
224 set_stemma_interactive( theSVG );
229 function set_stemma_interactive( svg_element ) {
230 $( "#root_tree_dialog_button_ok" ).click( function() {
231 // AJAX call goes here
233 $.each( $( 'ellipse', svg_element ), function(index) {
234 var ellipse = $(this);
235 var g = ellipse.parent( 'g' );
236 g.click( function(evt) {
237 if( typeof root_tree_dialog_timeout !== 'undefined' ) { clearTimeout( root_tree_dialog_timeout ) };
238 g.unbind( 'mouseleave' );
239 var dialog = $( '#root_tree_dialog' );
241 dialog.css( 'top', evt.pageY + 3 );
242 dialog.css( 'left', evt.pageX + 3 );
244 root_tree_dialog_timeout = setTimeout( function() {
245 $( '#root_tree_dialog' ).hide();
246 ellipse.removeClass( 'stemma_node_highlight' );
247 g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
250 g.mouseenter( function() {
251 $( 'ellipse.stemma_node_highlight' ).removeClass( 'stemma_node_highlight' );
252 ellipse.addClass( 'stemma_node_highlight' )
254 g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
258 // General-purpose error-handling function.
259 // TODO make sure this gets used throughout, where appropriate.
260 function display_error( jqXHR, el ) {
262 if( jqXHR.responseText == "" ) {
263 errmsg = "perhaps the server went down?"
267 errobj = jQuery.parseJSON( jqXHR.responseText );
268 errmsg = errobj.error;
269 } catch ( parse_err ) {
270 errmsg = "something went wrong on the server."
273 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
274 $(el).empty().append( msghtml ).show();
277 // Event to enable the upload button when a file has been selected
278 function file_selected( e ) {
279 if( e.files.length == 1 ) {
280 $('#upload_button').button('enable');
281 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
283 $('#upload_button').button('disable');
284 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
288 // Implement our own AJAX method that uses the features of XMLHttpRequest2
289 // but try to let it have a similar interface to jquery.post
290 // The data var needs to be a FormData() object.
291 // The callback will be given a single argument, which is the response data
292 // of the given type.
294 function post_xhr2( url, data, cb, type ) {
298 var xhr = new XMLHttpRequest();
299 // Set the expected response type
300 if( type === 'data' ) {
301 xhr.responseType = 'blob';
302 } else if( type === 'xml' ) {
303 xhr.responseType = 'document';
306 // Gin up an AJAX settings object
307 $.ajaxSetup({ url: url, type: 'POST' });
308 xhr.open( 'POST', url, true );
309 // Handle the results
310 xhr.onload = function( e ) {
311 // Get the response and parse it
312 // Call the callback with the response, whatever it was
314 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
316 if( type === 'json' ) {
317 resp = $.parseJSON( xhrs.responseText );
318 } else if ( type === 'xml' ) {
319 resp = xhrs.responseXML;
320 } else if ( type === 'text' ) {
321 resp = xhrs.responseText;
323 resp = xhrs.response;
327 // Trigger the ajaxError...
328 _trigger_ajaxerror( e );
331 xhr.onerror = _trigger_ajaxerror;
332 xhr.onabort = _trigger_ajaxerror;
336 function _trigger_ajaxerror( e ) {
338 var thrown = xhr.statusText || 'Request error';
339 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
342 function upload_new () {
343 // Serialize the upload form, get the file and attach it to the request,
344 // POST the lot and handle the response.
345 var newfile = $('#new_file').get(0).files[0];
346 var reader = new FileReader();
347 reader.onload = function( evt ) {
348 var data = new FormData();
349 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
350 data.append( o.name, o.value );
352 data.append( 'file', newfile );
353 var upload_url = _get_url([ 'newtradition' ]);
354 post_xhr2( upload_url, data, function( ret ) {
356 $('#upload-collation-dialog').dialog('close');
358 loadTradition( ret.id, ret.name, 1 );
359 } else if( ret.error ) {
360 $('#upload_status').empty().append(
361 $('<span>').attr('class', 'error').append( ret.error ) );
365 reader.onerror = function( evt ) {
366 var err_resp = 'File read error';
367 if( e.name == 'NotFoundError' ) {
368 err_resp = 'File not found';
369 } else if ( e.name == 'NotReadableError' ) {
370 err_resp == 'File unreadable - is it yours?';
371 } else if ( e.name == 'EncodingError' ) {
372 err_resp == 'File cannot be encoded - is it too long?';
373 } else if ( e.name == 'SecurityError' ) {
374 err_resp == 'File read security error';
376 // Fake a jqXHR object that we can pass to our generic error handler.
377 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
378 display_error( jqxhr, $('#upload_status') );
379 $('#upload_button').button('disable');
382 reader.readAsBinaryString( newfile );
385 // Utility function to neatly construct an application URL
386 function _get_url( els ) {
387 return basepath + els.join('/');
391 $(document).ready( function() {
392 // See if we have the browser functionality we need
393 // TODO Also think of a test for SVG readiness
394 if( !!window.FileReader && !!window.File ) {
395 $('#compatibility_check').empty();
398 // hide dialog not yet in use
399 $('#root_tree_dialog').hide();
401 // call out to load the directory div
402 $('#textinfo_container').hide();
403 $('#textinfo_waitbox').hide();
406 // Set up the textinfo edit dialog
407 $('#textinfo-edit-dialog').dialog({
413 Save: function (evt) {
414 $("#edit_textinfo_status").empty();
415 $(evt.target).button("disable");
416 var requrl = _get_url([ "textinfo", selectedTextID ]);
417 var reqparam = $('#edit_textinfo').serialize();
418 $.post( requrl, reqparam, function (data) {
419 // Reload the selected text fields
420 selectedTextInfo = data;
422 // Reenable the button and close the form
423 $(evt.target).button("enable");
424 $('#textinfo-edit-dialog').dialog('close');
428 $('#textinfo-edit-dialog').dialog('close');
432 $("#edit_textinfo_status").empty();
433 // Populate the form fields with the current values
434 // edit_(name, language, public, owner)
435 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
436 var fname = '#edit_' + k;
437 // Special case: language Default is basically language null
438 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
441 $(fname).val( selectedTextInfo[k] );
444 if( selectedTextInfo['public'] == true ) {
445 $('#edit_public').attr('checked','true');
447 $('#edit_public').removeAttr('checked');
450 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
451 $(event.target).parent().find('.ui-button').button("enable");
452 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
453 && ajaxSettings.type == 'POST' ) {
454 display_error( jqXHR, $("#edit_textinfo_status") );
459 // Set up the stemma editor dialog
460 $('#stemma-edit-dialog').dialog({
466 Save: function (evt) {
467 $("#edit_stemma_status").empty();
468 $(evt.target).button("disable");
469 var stemmaseq = $('#stemmaseq').val();
470 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
471 var reqparam = { 'dot': $('#dot_field').val() };
472 // TODO We need to stash the literal SVG string in stemmata
473 // somehow. Implement accept header on server side to decide
474 // whether to send application/json or application/xml?
475 $.post( requrl, reqparam, function (data) {
476 // We received a stemma SVG string in return.
477 // Update the current stemma sequence number
478 selectedStemmaID = data.stemmaid;
479 delete data.stemmaid;
480 // Stash the answer in the appropriate spot in our stemma array
481 stemmata[selectedStemmaID] = data;
482 // Display the new stemma
483 load_stemma( selectedStemmaID, true );
484 // Reenable the button and close the form
485 $(evt.target).button("enable");
486 $('#stemma-edit-dialog').dialog('close');
490 $('#stemma-edit-dialog').dialog('close');
493 open: function(evt) {
494 $("#edit_stemma_status").empty();
495 var stemmaseq = $('#stemmaseq').val();
496 if( stemmaseq == 'n' ) {
497 // If we are creating a new stemma, populate the textarea with a
499 $(evt.target).dialog('option', 'title', 'Add a new stemma')
500 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
502 // If we are editing a stemma, grab its stemmadot and populate the
503 // textarea with that.
504 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
505 $('#dot_field').val( 'Loading, please wait...' );
506 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
507 $.getJSON( doturl, function (data) {
508 // Re-insert the line breaks
509 var dotstring = data.dot.replace(/\|n/gm, "\n");
510 $('#dot_field').val( dotstring );
514 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
515 $(event.target).parent().find('.ui-button').button("enable");
516 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
517 && ajaxSettings.type == 'POST' ) {
518 display_error( jqXHR, $("#edit_stemma_status") );
522 $('#stemweb-ui-dialog').dialog({
528 Run: function (evt) {
529 $("#stemweb_run_status").empty();
530 $(evt.target).button("disable");
531 var requrl = _get_url([ "stemweb", "request" ]);
532 var reqparam = $('#call_stemweb').serialize();
533 // TODO We need to stash the literal SVG string in stemmata
534 // somehow. Implement accept header on server side to decide
535 // whether to send application/json or application/xml?
536 $.getJSON( requrl, reqparam, function (data) {
537 // Job ID is in data.jobid. TODO do something with it.
538 selectedTextInfo.stemweb_jobid = data.jobid;
539 $(evt.target).button("enable");
540 $('#stemweb-ui-dialog').dialog('close');
541 // Reload the current stemma to rejigger the buttons
542 load_stemma( selectedStemmaID, true );
546 $('#stemweb-ui-dialog').dialog('close');
549 create: function(evt) {
550 // Call out to Stemweb to get the algorithm options, with which we
551 // populate the form.
552 var algorithmTypes = {};
553 var algorithmArgs = {};
554 var requrl = _get_url([ "stemweb", "available" ]);
555 $.getJSON( requrl, function( data ) {
556 $.each( data, function( i, o ) {
557 if( o.model === 'algorithms.algorithm' ) {
558 // it's an algorithm.
559 algorithmTypes[ o.pk ] = o.fields;
560 } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
561 // it's an option for an algorithm that we should display.
562 algorithmArgs[ o.pk ] = o.fields;
565 // TODO if it is an empty object, disable Stemweb entirely.
566 if( !jQuery.isEmptyObject( algorithmTypes ) ) {
567 $.each( algorithmTypes, function( pk, fields ) {
568 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
569 $('#stemweb_algorithm').append( algopt );
571 // Set up the relevant options for whichever algorithm is chosen.
572 // "key" -> form name, option ID "stemweb_$key_opt"
573 // "name" -> form label
574 $('#stemweb_algorithm').change( function() {
575 var pk = $(this).val();
576 $('#stemweb_runtime_options').empty();
577 $.each( algorithmTypes[pk].args, function( i, apk ) {
578 var argInfo = algorithmArgs[apk];
580 // Make the element ID
581 var optId = 'stemweb_' + argInfo.key + '_opt';
583 var optLabel = $('<label>').attr( 'for', optId )
584 .append( argInfo.name + ": " );
586 var argType = argInfo.value;
587 if( argType === 'positive_integer' ) {
588 // Make it an input field of smallish size.
589 optCtrl = $('<input>').attr( 'size', 4 );
590 } else if ( argType === 'boolean' ) {
591 // Make it a checkbox.
592 optCtrl = $('<checkbox>');
594 // Add the name and element ID
595 optCtrl.attr( 'name', argInfo.key ).attr( 'id', optId );
596 // Append the label and the option itself to the form.
597 $('#stemweb_runtime_options').append( optLabel )
598 .append( optCtrl ).append( $('<br>') );
602 $('#stemweb_algorithm').change();
605 // Prime the initial options
607 open: function(evt) {
608 $('#stemweb_run_status').empty();
609 $('#stemweb_tradition').attr('value', selectedTextID );
611 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
612 $(event.target).parent().find('.ui-button').button("enable");
613 if( ajaxSettings.url.indexOf( 'stemweb/request' ) > -1 ) {
614 display_error( jqXHR, $("#stemweb_run_status") );
618 $('#upload-collation-dialog').dialog({
628 $('#upload_status').empty();
629 $('#upload_button').button("disable");
635 id: 'pick_file_button',
637 $('#new_file').click();
641 $('#upload-collation-dialog').dialog('close');
645 // Set the upload button to its correct state based on
646 // whether a file is loaded
647 file_selected( $('#new_file').get(0) );
648 $('#upload_status').empty();
650 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
651 // Reset button state
652 file_selected( $('#new_file').get(0) );
653 // Display error message if applicable
654 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
655 && ajaxSettings.type == 'POST' ) {
656 display_error( jqXHR, $("#upload_status") );
660 $('#stemma_graph').mousedown( function(evt) {
661 evt.stopPropagation();
662 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
663 $('body').mousemove( function(evt) {
664 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
665 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
666 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
667 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
668 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
669 var g = $('g.graph', svg_root).get(0);
670 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
671 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
672 g.setAttribute( 'transform', new_transform );
673 evt.returnValue = false;
674 evt.preventDefault();
677 $('body').mouseup( function(evt) {
678 $('body').unbind('mousemove');
679 $('body').unbind('mouseup');
683 $('#stemma_graph').mousewheel(function (event, delta) {
684 event.returnValue = false;
685 event.preventDefault();
686 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
687 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
688 if( delta < -9 ) { delta = -9 };
689 var z = 1 + delta/10;
690 z = delta > 0 ? 1 : -1;
691 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
692 var g = $('g.graph', svg_root).get(0);
693 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
694 var scaleLevel = z/10;
695 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
696 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
697 g.setAttribute( 'transform', new_transform );