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