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