zap last Stemweb alert box; fix related UI logic
[scpubgit/stemmaweb.git] / root / js / componentload.js
CommitLineData
3f9d7ae5 1// Global state variables
2var selectedTextID;
3var selectedTextInfo;
6aabefa3 4var selectedTextEditable;
3f9d7ae5 5var selectedStemmaID = -1;
6var stemmata = [];
7
8// Load the names of the appropriate traditions into the directory div.
9function refreshDirectory () {
10 var lmesg = $('#loading_message').clone();
11 $('#directory').empty().append( lmesg.contents() );
12 $('#directory').load( _get_url(["directory"]),
13 function(response, status, xhr) {
14 if (status == "error") {
15 var msg = "An error occurred: ";
16 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
17 } else {
18 if( textOnLoad != "" ) {
19 // Call the click callback for the relevant text, if it is
20 // in the page.
21 $('#'+textOnLoad).click();
22 textOnLoad = "";
23 }
24 }
25 }
26 );
27}
28
29// Load a tradition with its information and stemmata into the tradition
30// view pane. Calls load_textinfo.
98a45925 31function loadTradition( textid, textname, editable ) {
32 selectedTextID = textid;
6aabefa3 33 selectedTextEditable = editable;
98a45925 34 // First insert the placeholder image and register an error handler
04469f3e 35 $('#textinfo_load_status').empty();
5f0eda3f 36 $('#stemma_graph').empty();
98a45925 37 $('#textinfo_waitbox').show();
75354c3a 38 $('#textinfo_container').hide().ajaxError(
39 function(event, jqXHR, ajaxSettings, thrownError) {
40 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET' ) {
41 $('#textinfo_waitbox').hide();
42 $('#textinfo_container').show();
43 display_error( jqXHR, $("#textinfo_load_status") );
98a45925 44 }
75354c3a 45 });
46
47 // Hide the functionality that is irrelevant
48 if( editable ) {
ce1c5863 49 $('#open_stemma_add').show();
ce1c5863 50 $('#open_textinfo_edit').show();
cbd23059 51 $('#relatebutton_label').text('View collation and edit relationships');
75354c3a 52 } else {
ce1c5863 53 $('#open_stemma_add').hide();
db234220 54 $('#open_stemweb_ui').hide();
c2b80bba 55 $('#query_stemweb_ui').hide();
ce1c5863 56 $('#open_textinfo_edit').hide();
cbd23059 57 $('#relatebutton_label').text('View collation and relationships');
75354c3a 58 }
59
62723740 60 // Then get and load the actual content.
98a45925 61 // TODO: scale #stemma_graph both horizontally and vertically
f6a8db89 62 // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
3f9d7ae5 63 $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
98a45925 64 // Add the scalar data
75354c3a 65 selectedTextInfo = textdata;
66 load_textinfo();
63378fe0 67 // Add the stemma(ta)
98a45925 68 stemmata = textdata.stemmata;
69 if( stemmata.length ) {
70 selectedStemmaID = 0;
65a0c9c6 71 } else {
57e3a008 72 selectedStemmaID = -1;
65a0c9c6 73 }
6aabefa3 74 load_stemma( selectedStemmaID );
98a45925 75 // Set up the relationship mapper button
3f9d7ae5 76 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
38627d20 77 // Set up the download button
78 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
79 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
98a45925 80 });
81}
82
3f9d7ae5 83// Load the metadata about a tradition into the appropriate div.
75354c3a 84function load_textinfo() {
85 $('#textinfo_waitbox').hide();
86 $('#textinfo_load_status').empty();
87 $('#textinfo_container').show();
24e64429 88 // The tradition name should appear here and should be identical in the
89 // corresponding directory span. In case the name was just changed...
75354c3a 90 $('.texttitle').empty().append( selectedTextInfo.name );
24e64429 91 $('#' + selectedTextID).empty().append( selectedTextInfo.name );
75354c3a 92 // Witnesses
93 $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
94 $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
95 // Who the owner is
96 $('#owner_id').empty().append('no one');
97 if( selectedTextInfo.owner ) {
897a22fc 98 var owneremail = selectedTextInfo.owner;
99 var chop = owneremail.indexOf( '@' );
100 if( chop > -1 ) {
101 owneremail = owneremail.substr( 0, chop + 1 ) + '...';
102 }
103 $('#owner_id').empty().append( owneremail );
75354c3a 104 }
105 // Whether or not it is public
106 $('#not_public').empty();
107 if( selectedTextInfo['public'] == false ) {
108 $('#not_public').append('NOT ');
109 }
110 // What language setting it has, if any
111 $('#marked_language').empty().append('no language set');
112 if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
113 $('#marked_language').empty().append( selectedTextInfo.language );
114 }
115}
116
3f9d7ae5 117// Enable / disable the appropriate buttons for paging through the stemma.
6aabefa3 118function show_stemmapager () {
bf81fb57 119 $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
120 $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
65a0c9c6 121 if( selectedStemmaID > 0 ) {
122 $('.pager_left_button').click( function () {
6aabefa3 123 load_stemma( selectedStemmaID - 1, selectedTextEditable );
bf81fb57 124 }).removeClass( 'greyed_out' );
65a0c9c6 125 }
126 if( selectedStemmaID + 1 < stemmata.length ) {
127 $('.pager_right_button').click( function () {
6aabefa3 128 load_stemma( selectedStemmaID + 1, selectedTextEditable );
bf81fb57 129 }).removeClass( 'greyed_out' );
65a0c9c6 130 }
131}
132
3f9d7ae5 133// Load a given stemma SVG into the stemmagraph box.
6aabefa3 134function load_stemma( idx ) {
65a0c9c6 135 // Load the stemma at idx
136 selectedStemmaID = idx;
6aabefa3 137 show_stemmapager( selectedTextEditable );
63378fe0 138 $('#open_stemma_edit').hide();
139 $('#run_stexaminer').hide();
140 $('#stemma_identifier').empty();
c2b80bba 141 // Add the relevant Stemweb functionality
6aabefa3 142 if( selectedTextEditable ) {
509e94bc 143 switch_stemweb_ui();
c2b80bba 144 }
98a45925 145 if( idx > -1 ) {
63378fe0 146 // Load the stemma and its properties
ec2f89ff 147 var stemmadata = stemmata[idx];
6aabefa3 148 if( selectedTextEditable ) {
63378fe0 149 $('#open_stemma_edit').show();
150 }
151 if( stemmadata.directed ) {
152 // Stexaminer submit action
153 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
154 $('#run_stexaminer').attr( 'action', stexpath );
155 $('#run_stexaminer').show();
156 }
157 loadSVG( stemmadata.svg );
158 $('#stemma_identifier').text( stemmadata.name );
40803b80 159 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
98a45925 160 }
5ba6c2b4 161}
75354c3a 162
509e94bc 163function switch_stemweb_ui() {
164 if( selectedTextInfo.stemweb_jobid == 0 ) {
165 // We want to run Stemweb.
166 $('#open_stemweb_ui').show();
509e94bc 167 $('#query_stemweb_ui').hide();
e6d34d3e 168 if( ! $('#stemweb-ui-dialog').dialog('isOpen') ) {
169 $('#call_stemweb').show()
170 $('#stemweb_run_button').show();
171 }
509e94bc 172 } else {
173 $('#query_stemweb_ui').show();
174 $('#open_stemweb_ui').hide();
175 $('#call_stemweb').hide();
176 $('#stemweb_run_button').hide();
177 }
178}
179
c2b80bba 180function query_stemweb_progress() {
181 var requrl = _get_url([ "stemweb", "query", selectedTextInfo.stemweb_jobid ]);
509e94bc 182 $('#stemweb-ui-dialog').dialog('open');
183 $('#stemweb_run_status').empty().append(
184 _make_message( 'notification', 'Querying Stemweb for calculation progress...') );
c2b80bba 185 $.getJSON( requrl, function (data) {
3cb9d9c0 186 process_stemweb_result( data );
187 });
188}
189
190function process_stemweb_result(data) {
191 // Look for a status message, either success, running, or notfound.
192 if( data.status === 'success' ) {
193 // Add the new stemmata to the textinfo and tell the user.
194 selectedTextInfo.stemweb_jobid = 0;
195 if( data.stemmata.length > 0 ) {
196 stemmata = stemmata.concat( data.stemmata );
197 if( selectedStemmaID == -1 ) {
198 // We have a stemma for the first time; load the first one.
199 load_stemma( 0, true );
c2b80bba 200 } else {
3cb9d9c0 201 // Move to the index of the first added stemma.
202 var newIdx = stemmata.length - data.stemmata.length;
203 load_stemma( newIdx, true );
509e94bc 204 }
e4fd6366 205 // Hide the call dialog no matter how we got here
206 $('#call_stemweb').hide()
207 $('#stemweb_run_button').hide();
509e94bc 208 $('#stemweb_run_status').empty().append(
209 _make_message( 'notification', 'You have one or more new stemmata!' ) );
3cb9d9c0 210 } else {
509e94bc 211 $('#stemweb_run_status').empty().append(
212 _make_message( 'warning', 'Stemweb run finished with no stemmata...huh?!' ) );
c2b80bba 213 }
3cb9d9c0 214 } else if( data.status === 'running' ) {
215 // Just tell the user.
509e94bc 216 $('#stemweb_run_status').empty().append(
e4fd6366 217 _make_message( 'warning', 'Your Stemweb query is still running!' ) );
3cb9d9c0 218 } else if( data.status === 'notfound' ) {
219 // Ask the user to refresh, for now.
509e94bc 220 $('#stemweb_run_status').empty().append(
221 _make_message( 'warning', 'Your Stemweb query probably finished and reported back. Please reload to check.' ) );
222 } else if( data.status === 'failed' ) {
223 selectedTextInfo.stemweb_jobid = 0;
224 failureMsg = 'Your stemweb query failed';
225 if( data.message ) {
226 failureMsg = failureMsg + ' with the following message: ' + data.message
e6d34d3e 227 } else {
228 failureMsg = failureMsg + ' without telling us why.'
509e94bc 229 }
230 $('#stemweb_run_status').empty().append(
e6d34d3e 231 _make_message( 'error', failureMsg ) );
3cb9d9c0 232 }
509e94bc 233}
234
235function _make_message( type, msg ) {
236 theMessage = $('<span>').attr( 'class', type );
237 theMessage.append( msg );
238 return theMessage;
c2b80bba 239}
240
bd3ccd15 241// Load the SVG we are given
242function loadSVG(svgData) {
243 var svgElement = $('#stemma_graph');
244
245 $(svgElement).svg('destroy');
246
247 $(svgElement).svg({
248 loadURL: svgData,
249 onLoad : function () {
250 var theSVG = svgElement.find('svg');
251 var svgoffset = theSVG.offset();
bd3ccd15 252 var browseroffset = 1;
23f8bfc2 253 // Firefox needs a different offset, stupidly enough
bd3ccd15 254 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
23f8bfc2 255 browseroffset = 3; // works for tall images
256 // ...but if the SVG is wider than it is tall, Firefox treats
257 // the top as being the top of the graph, loaded into the middle
258 // of the canvas, but then the margin at the top of the canvas
259 // extends upward. So we have to find the actual top of the canvas
260 // and correct for *that* instead.
261 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
262 if( vbdim.height < vbdim.width ) {
263 var vbscale = svgElement.width() / vbdim.width;
264 var vbrealheight = vbdim.height * vbscale;
265 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
266 }
bd3ccd15 267 }
268 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
bd3ccd15 269 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
b63f3a77 270 set_stemma_interactive( theSVG );
bd3ccd15 271 }
272 });
273}
274
b63f3a77 275function set_stemma_interactive( svg_element ) {
6aabefa3 276 if( selectedTextEditable ) {
277 $( "#root_tree_dialog_button_ok" ).click( function() {
278 var requrl = _get_url([ "stemmaroot", selectedTextID, selectedStemmaID ]);
9f4b205a 279 var targetnode = $('#root_tree_dialog').data( 'selectedNode' );
6aabefa3 280 $.post( requrl, { root: targetnode }, function (data) {
281 // Reload the new stemma
282 stemmata[selectedStemmaID] = data;
283 load_stemma( selectedStemmaID );
284 // Put away the dialog
9f4b205a 285 $('#root_tree_dialog').data( 'selectedNode', null ).hide();
6aabefa3 286 } );
287 } ).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
288 if( ajaxSettings.url.indexOf( 'stemmaroot' ) > -1
289 && ajaxSettings.type == 'POST' ) {
290 display_error( jqXHR, $("#stemma_load_status") );
291 }
292 } );
293 // TODO Clear error at some appropriate point
294 $.each( $( 'ellipse', svg_element ), function(index) {
295 var ellipse = $(this);
296 var g = ellipse.parent( 'g' );
297 g.click( function(evt) {
298 if( typeof root_tree_dialog_timeout !== 'undefined' ) { clearTimeout( root_tree_dialog_timeout ) };
299 g.unbind( 'mouseleave' );
300 var dialog = $( '#root_tree_dialog' );
9f4b205a 301 // Note which node triggered the dialog
302 dialog.data( 'selectedNode', g.attr('id') );
303 // Position the dialog
6aabefa3 304 dialog.hide();
305 dialog.css( 'top', evt.pageY + 3 );
306 dialog.css( 'left', evt.pageX + 3 );
307 dialog.show();
308 root_tree_dialog_timeout = setTimeout( function() {
9f4b205a 309 $( '#root_tree_dialog' ).data( 'selectedNode', null ).hide();
6aabefa3 310 ellipse.removeClass( 'stemma_node_highlight' );
311 g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
312 }, 3000 );
313 } );
314 g.mouseenter( function() {
315 $( 'ellipse.stemma_node_highlight' ).removeClass( 'stemma_node_highlight' );
316 ellipse.addClass( 'stemma_node_highlight' )
317 } );
318 g.mouseleave( function() { ellipse.removeClass( 'stemma_node_highlight' ) } );
319 } );
320 }
b63f3a77 321}
39b8b37b 322
3f9d7ae5 323// General-purpose error-handling function.
324// TODO make sure this gets used throughout, where appropriate.
75354c3a 325function display_error( jqXHR, el ) {
ce1c5863 326 var errmsg;
327 if( jqXHR.responseText == "" ) {
328 errmsg = "perhaps the server went down?"
75354c3a 329 } else {
ce1c5863 330 var errobj;
331 try {
332 errobj = jQuery.parseJSON( jqXHR.responseText );
333 errmsg = errobj.error;
334 } catch ( parse_err ) {
335 errmsg = "something went wrong on the server."
336 }
75354c3a 337 }
ce1c5863 338 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
75354c3a 339 $(el).empty().append( msghtml ).show();
3f9d7ae5 340}
341
e0b90236 342// Event to enable the upload button when a file has been selected
343function file_selected( e ) {
344 if( e.files.length == 1 ) {
345 $('#upload_button').button('enable');
ab0d1218 346 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
e0b90236 347 } else {
348 $('#upload_button').button('disable');
ab0d1218 349 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
e0b90236 350 }
351}
352
2ece58b3 353// Implement our own AJAX method that uses the features of XMLHttpRequest2
354// but try to let it have a similar interface to jquery.post
355// The data var needs to be a FormData() object.
356// The callback will be given a single argument, which is the response data
357// of the given type.
358
359function post_xhr2( url, data, cb, type ) {
360 if( !type ) {
361 type = 'json';
362 }
363 var xhr = new XMLHttpRequest();
364 // Set the expected response type
365 if( type === 'data' ) {
366 xhr.responseType = 'blob';
367 } else if( type === 'xml' ) {
368 xhr.responseType = 'document';
369 }
370 // Post the form
371 // Gin up an AJAX settings object
372 $.ajaxSetup({ url: url, type: 'POST' });
373 xhr.open( 'POST', url, true );
374 // Handle the results
375 xhr.onload = function( e ) {
376 // Get the response and parse it
377 // Call the callback with the response, whatever it was
378 var xhrs = e.target;
379 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
380 var resp;
381 if( type === 'json' ) {
382 resp = $.parseJSON( xhrs.responseText );
383 } else if ( type === 'xml' ) {
384 resp = xhrs.responseXML;
385 } else if ( type === 'text' ) {
386 resp = xhrs.responseText;
387 } else {
388 resp = xhrs.response;
389 }
390 cb( resp );
391 } else {
392 // Trigger the ajaxError...
393 _trigger_ajaxerror( e );
394 }
395 };
396 xhr.onerror = _trigger_ajaxerror;
397 xhr.onabort = _trigger_ajaxerror;
398 xhr.send( data );
399}
400
401function _trigger_ajaxerror( e ) {
402 var xhr = e.target;
403 var thrown = xhr.statusText || 'Request error';
404 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
405}
406
e0b90236 407function upload_new () {
408 // Serialize the upload form, get the file and attach it to the request,
409 // POST the lot and handle the response.
410 var newfile = $('#new_file').get(0).files[0];
411 var reader = new FileReader();
412 reader.onload = function( evt ) {
2ece58b3 413 var data = new FormData();
414 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
415 data.append( o.name, o.value );
416 });
417 data.append( 'file', newfile );
e0b90236 418 var upload_url = _get_url([ 'newtradition' ]);
2ece58b3 419 post_xhr2( upload_url, data, function( ret ) {
e0b90236 420 if( ret.id ) {
421 $('#upload-collation-dialog').dialog('close');
422 refreshDirectory();
423 loadTradition( ret.id, ret.name, 1 );
424 } else if( ret.error ) {
425 $('#upload_status').empty().append(
426 $('<span>').attr('class', 'error').append( ret.error ) );
427 }
2ece58b3 428 }, 'json' );
e0b90236 429 };
430 reader.onerror = function( evt ) {
431 var err_resp = 'File read error';
432 if( e.name == 'NotFoundError' ) {
433 err_resp = 'File not found';
434 } else if ( e.name == 'NotReadableError' ) {
435 err_resp == 'File unreadable - is it yours?';
436 } else if ( e.name == 'EncodingError' ) {
437 err_resp == 'File cannot be encoded - is it too long?';
438 } else if ( e.name == 'SecurityError' ) {
439 err_resp == 'File read security error';
440 }
441 // Fake a jqXHR object that we can pass to our generic error handler.
442 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
443 display_error( jqxhr, $('#upload_status') );
444 $('#upload_button').button('disable');
445 }
446
447 reader.readAsBinaryString( newfile );
3f9d7ae5 448}
449
450// Utility function to neatly construct an application URL
451function _get_url( els ) {
452 return basepath + els.join('/');
453}
454
6aabefa3 455// TODO Attach unified ajaxError handler to document
3f9d7ae5 456$(document).ready( function() {
50778a5d 457 // See if we have the browser functionality we need
458 // TODO Also think of a test for SVG readiness
7c25980f 459 if( !!window.FileReader && !!window.File ) {
50778a5d 460 $('#compatibility_check').empty();
461 }
b63f3a77 462
463 // hide dialog not yet in use
464 $('#root_tree_dialog').hide();
50778a5d 465
3f9d7ae5 466 // call out to load the directory div
467 $('#textinfo_container').hide();
468 $('#textinfo_waitbox').hide();
469 refreshDirectory();
470
471 // Set up the textinfo edit dialog
472 $('#textinfo-edit-dialog').dialog({
473 autoOpen: false,
474 height: 200,
475 width: 300,
476 modal: true,
477 buttons: {
478 Save: function (evt) {
479 $("#edit_textinfo_status").empty();
932277e1 480 var mybuttons = $(evt.target).closest('button').parent().find('button');
481 mybuttons.button( 'disable' );
3f9d7ae5 482 var requrl = _get_url([ "textinfo", selectedTextID ]);
483 var reqparam = $('#edit_textinfo').serialize();
484 $.post( requrl, reqparam, function (data) {
485 // Reload the selected text fields
486 selectedTextInfo = data;
487 load_textinfo();
488 // Reenable the button and close the form
932277e1 489 mybuttons.button("enable");
3f9d7ae5 490 $('#textinfo-edit-dialog').dialog('close');
491 }, 'json' );
492 },
493 Cancel: function() {
494 $('#textinfo-edit-dialog').dialog('close');
495 }
496 },
497 open: function() {
498 $("#edit_textinfo_status").empty();
499 // Populate the form fields with the current values
500 // edit_(name, language, public, owner)
501 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
502 var fname = '#edit_' + k;
503 // Special case: language Default is basically language null
504 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
505 $(fname).val( "" );
506 } else {
507 $(fname).val( selectedTextInfo[k] );
508 }
509 });
510 if( selectedTextInfo['public'] == true ) {
511 $('#edit_public').attr('checked','true');
512 } else {
513 $('#edit_public').removeAttr('checked');
514 }
515 },
516 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
517 $(event.target).parent().find('.ui-button').button("enable");
518 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
519 && ajaxSettings.type == 'POST' ) {
520 display_error( jqXHR, $("#edit_textinfo_status") );
521 }
522 });
523
524
525 // Set up the stemma editor dialog
526 $('#stemma-edit-dialog').dialog({
527 autoOpen: false,
528 height: 700,
529 width: 600,
530 modal: true,
531 buttons: {
532 Save: function (evt) {
533 $("#edit_stemma_status").empty();
932277e1 534 var mybuttons = $(evt.target).closest('button').parent().find('button');
535 mybuttons.button( 'disable' );
3f9d7ae5 536 var stemmaseq = $('#stemmaseq').val();
537 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
538 var reqparam = { 'dot': $('#dot_field').val() };
539 // TODO We need to stash the literal SVG string in stemmata
540 // somehow. Implement accept header on server side to decide
541 // whether to send application/json or application/xml?
542 $.post( requrl, reqparam, function (data) {
543 // We received a stemma SVG string in return.
544 // Update the current stemma sequence number
545 selectedStemmaID = data.stemmaid;
be536c89 546 delete data.stemmaid;
547 // Stash the answer in the appropriate spot in our stemma array
548 stemmata[selectedStemmaID] = data;
3f9d7ae5 549 // Display the new stemma
63378fe0 550 load_stemma( selectedStemmaID, true );
3f9d7ae5 551 // Reenable the button and close the form
932277e1 552 mybuttons.button("enable");
3f9d7ae5 553 $('#stemma-edit-dialog').dialog('close');
554 }, 'json' );
555 },
556 Cancel: function() {
557 $('#stemma-edit-dialog').dialog('close');
558 }
559 },
560 open: function(evt) {
561 $("#edit_stemma_status").empty();
562 var stemmaseq = $('#stemmaseq').val();
563 if( stemmaseq == 'n' ) {
564 // If we are creating a new stemma, populate the textarea with a
565 // bare digraph.
566 $(evt.target).dialog('option', 'title', 'Add a new stemma')
db234220 567 $('#dot_field').val( "digraph \"NAME STEMMA HERE\" {\n\n}" );
3f9d7ae5 568 } else {
569 // If we are editing a stemma, grab its stemmadot and populate the
570 // textarea with that.
571 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
572 $('#dot_field').val( 'Loading, please wait...' );
573 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
574 $.getJSON( doturl, function (data) {
575 // Re-insert the line breaks
576 var dotstring = data.dot.replace(/\|n/gm, "\n");
577 $('#dot_field').val( dotstring );
578 });
579 }
580 },
581 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
582 $(event.target).parent().find('.ui-button').button("enable");
583 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
584 && ajaxSettings.type == 'POST' ) {
585 display_error( jqXHR, $("#edit_stemma_status") );
586 }
587 });
db234220 588
589 $('#stemweb-ui-dialog').dialog({
590 autoOpen: false,
e239d45f 591 height: 'auto',
509e94bc 592 width: 520,
db234220 593 modal: true,
594 buttons: {
509e94bc 595 Run: {
596 id: 'stemweb_run_button',
597 text: 'Run',
598 click: function (evt) {
db234220 599 $("#stemweb_run_status").empty();
932277e1 600 var mybuttons = $(evt.target).closest('button').parent().find('button');
601 mybuttons.button( 'disable' );
70744367 602 var requrl = _get_url([ "stemweb", "request" ]);
603 var reqparam = $('#call_stemweb').serialize();
db234220 604 // TODO We need to stash the literal SVG string in stemmata
605 // somehow. Implement accept header on server side to decide
606 // whether to send application/json or application/xml?
70744367 607 $.getJSON( requrl, reqparam, function (data) {
932277e1 608 mybuttons.button("enable");
3cb9d9c0 609 if( 'jobid' in data ) {
610 // There is a pending job.
611 selectedTextInfo.stemweb_jobid = data.jobid;
e4fd6366 612 $('#stemweb_run_status').empty().append(
613 _make_message( 'notification', "Your request has been submitted to Stemweb.\nThe resulting tree will appear in due course." ) );
3cb9d9c0 614 // Reload the current stemma to rejigger the buttons
e4fd6366 615 switch_stemweb_ui();
3cb9d9c0 616 } else {
617 // We appear to have an answer; process it.
618 process_stemweb_result( data );
619 }
db234220 620 }, 'json' );
509e94bc 621 },
db234220 622 },
509e94bc 623 Close: {
624 id: 'stemweb_close_button',
625 text: 'Close',
626 click: function() {
e6d34d3e 627 $('#stemweb-ui-dialog').dialog('close');
628 switch_stemweb_ui();
509e94bc 629 },
630 },
db234220 631 },
632 create: function(evt) {
633 // Call out to Stemweb to get the algorithm options, with which we
634 // populate the form.
635 var algorithmTypes = {};
636 var algorithmArgs = {};
66458003 637 var requrl = _get_url([ "stemweb", "available" ]);
638 $.getJSON( requrl, function( data ) {
639 $.each( data, function( i, o ) {
640 if( o.model === 'algorithms.algorithm' ) {
641 // it's an algorithm.
642 algorithmTypes[ o.pk ] = o.fields;
643 } else if( o.model == 'algorithms.algorithmarg' && o.fields.external ) {
644 // it's an option for an algorithm that we should display.
645 algorithmArgs[ o.pk ] = o.fields;
70744367 646 }
647 });
66458003 648 // TODO if it is an empty object, disable Stemweb entirely.
649 if( !jQuery.isEmptyObject( algorithmTypes ) ) {
650 $.each( algorithmTypes, function( pk, fields ) {
651 var algopt = $('<option>').attr( 'value', pk ).append( fields.name );
652 $('#stemweb_algorithm').append( algopt );
653 });
654 // Set up the relevant options for whichever algorithm is chosen.
655 // "key" -> form name, option ID "stemweb_$key_opt"
656 // "name" -> form label
e239d45f 657 $('#stemweb_algorithm_help').click( function() {
658 $('#stemweb_algorithm_desc_text').toggle( 'blind' );
659 });
66458003 660 $('#stemweb_algorithm').change( function() {
661 var pk = $(this).val();
d9d6b62b 662 // Display a link to the popup description, and fill in
663 // the description itself, if we have one.
664 if( 'desc' in algorithmTypes[pk] ) {
665 $('#stemweb_algorithm_desc_text').empty().append( algorithmTypes[pk].desc );
666 $('#stemweb_algorithm_desc').show();
667 } else {
668 $('#stemweb_algorithm_desc').hide();
669 }
66458003 670 $('#stemweb_runtime_options').empty();
671 $.each( algorithmTypes[pk].args, function( i, apk ) {
672 var argInfo = algorithmArgs[apk];
673 if( argInfo ) {
674 // Make the element ID
675 var optId = 'stemweb_' + argInfo.key + '_opt';
676 // Make the label
677 var optLabel = $('<label>').attr( 'for', optId )
678 .append( argInfo.name + ": " );
679 var optCtrl;
680 var argType = argInfo.value;
681 if( argType === 'positive_integer' ) {
682 // Make it an input field of smallish size.
683 optCtrl = $('<input>').attr( 'size', 4 );
684 } else if ( argType === 'boolean' ) {
685 // Make it a checkbox.
686 optCtrl = $('<checkbox>');
687 }
688 // Add the name and element ID
689 optCtrl.attr( 'name', argInfo.key ).attr( 'id', optId );
690 // Append the label and the option itself to the form.
691 $('#stemweb_runtime_options').append( optLabel )
692 .append( optCtrl ).append( $('<br>') );
693 }
694 });
695 });
696 $('#stemweb_algorithm').change();
697 }
70744367 698 });
699 // Prime the initial options
db234220 700 },
701 open: function(evt) {
70744367 702 $('#stemweb_run_status').empty();
b8f3a8c8 703 $('#stemweb_tradition').attr('value', selectedTextID );
509e94bc 704 if( selectedTextInfo.stemweb_jobid == 0 ) {
705 $('#stemweb_merge_reltypes').empty();
706 $.each( selectedTextInfo.reltypes, function( i, r ) {
707 var relation_opt = $('<option>').attr( 'value', r ).append( r );
708 $('#stemweb_merge_reltypes').append( relation_opt );
709 });
710 $('#stemweb_merge_reltypes').multiselect({
711 header: false,
712 selectedList: 3
713 });
714 }
db234220 715 },
716 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
717 $(event.target).parent().find('.ui-button').button("enable");
509e94bc 718 if( ajaxSettings.url.indexOf( 'stemweb/' ) > -1 ) {
db234220 719 display_error( jqXHR, $("#stemweb_run_status") );
720 }
721 });
3f9d7ae5 722
6cf17f04 723 // Set up the download dialog
724 $('#download-dialog').dialog({
725 autoOpen: false,
726 height: 150,
727 width: 300,
728 modal: true,
729 buttons: {
730 Download: function (evt) {
731 var dlurl = _get_url([ "download", $('#download_tradition').val(), $('#download_format').val() ]);
732 window.location = dlurl;
6cf17f04 733 },
8e26de0f 734 Done: function() {
6cf17f04 735 $('#download-dialog').dialog('close');
736 }
737 },
738 open: function() {
739 $('#download_tradition').attr('value', selectedTextID );
740 },
741 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
742 $(event.target).parent().find('.ui-button').button("enable");
743 if( ajaxSettings.url.indexOf( 'download' ) > -1
744 && ajaxSettings.type == 'POST' ) {
745 display_error( jqXHR, $("#download_status") );
746 }
747 });
748
3f9d7ae5 749 $('#upload-collation-dialog').dialog({
750 autoOpen: false,
e0b90236 751 height: 360,
3f9d7ae5 752 width: 480,
753 modal: true,
754 buttons: {
3f9d7ae5 755 upload: {
756 text: 'Upload',
757 id: 'upload_button',
758 click: function() {
759 $('#upload_status').empty();
e0b90236 760 $('#upload_button').button("disable");
761 upload_new();
3f9d7ae5 762 }
763 },
ab0d1218 764 pick_file: {
765 text: 'Pick File',
766 id: 'pick_file_button',
767 click: function() {
768 $('#new_file').click();
769 }
770 },
3f9d7ae5 771 Cancel: function() {
772 $('#upload-collation-dialog').dialog('close');
773 }
774 },
e0b90236 775 open: function() {
776 // Set the upload button to its correct state based on
777 // whether a file is loaded
778 file_selected( $('#new_file').get(0) );
2ece58b3 779 $('#upload_status').empty();
3f9d7ae5 780 }
e0b90236 781 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
782 // Reset button state
783 file_selected( $('#new_file').get(0) );
784 // Display error message if applicable
785 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
786 && ajaxSettings.type == 'POST' ) {
787 display_error( jqXHR, $("#upload_status") );
788 }
789 });;
3f9d7ae5 790
791 $('#stemma_graph').mousedown( function(evt) {
792 evt.stopPropagation();
793 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
794 $('body').mousemove( function(evt) {
795 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
796 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
797 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
798 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
799 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
800 var g = $('g.graph', svg_root).get(0);
801 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
802 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
803 g.setAttribute( 'transform', new_transform );
804 evt.returnValue = false;
805 evt.preventDefault();
806 return false;
807 });
808 $('body').mouseup( function(evt) {
809 $('body').unbind('mousemove');
810 $('body').unbind('mouseup');
811 });
812 });
813
814 $('#stemma_graph').mousewheel(function (event, delta) {
815 event.returnValue = false;
816 event.preventDefault();
817 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
818 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
819 if( delta < -9 ) { delta = -9 };
820 var z = 1 + delta/10;
821 z = delta > 0 ? 1 : -1;
822 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
823 var g = $('g.graph', svg_root).get(0);
824 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
825 var scaleLevel = z/10;
826 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
827 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
828 g.setAttribute( 'transform', new_transform );
829 }
830 });
831
832});