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