Only show stexaminer button for directed graphs
[scpubgit/stemmaweb.git] / root / js / componentload.js
CommitLineData
3f9d7ae5 1// Global state variables
2var selectedTextID;
3var selectedTextInfo;
4var selectedStemmaID = -1;
5var stemmata = [];
6
7// Load the names of the appropriate traditions into the directory div.
8function refreshDirectory () {
9 var lmesg = $('#loading_message').clone();
10 $('#directory').empty().append( lmesg.contents() );
11 $('#directory').load( _get_url(["directory"]),
12 function(response, status, xhr) {
13 if (status == "error") {
14 var msg = "An error occurred: ";
15 $("#directory").html(msg + xhr.status + " " + xhr.statusText);
16 } else {
17 if( textOnLoad != "" ) {
18 // Call the click callback for the relevant text, if it is
19 // in the page.
20 $('#'+textOnLoad).click();
21 textOnLoad = "";
22 }
23 }
24 }
25 );
26}
27
28// Load a tradition with its information and stemmata into the tradition
29// view pane. Calls load_textinfo.
98a45925 30function loadTradition( textid, textname, editable ) {
31 selectedTextID = textid;
32 // First insert the placeholder image and register an error handler
04469f3e 33 $('#textinfo_load_status').empty();
5f0eda3f 34 $('#stemma_graph').empty();
98a45925 35 $('#textinfo_waitbox').show();
75354c3a 36 $('#textinfo_container').hide().ajaxError(
37 function(event, jqXHR, ajaxSettings, thrownError) {
38 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1 && ajaxSettings.type == 'GET' ) {
39 $('#textinfo_waitbox').hide();
40 $('#textinfo_container').show();
41 display_error( jqXHR, $("#textinfo_load_status") );
98a45925 42 }
75354c3a 43 });
44
45 // Hide the functionality that is irrelevant
46 if( editable ) {
ce1c5863 47 $('#open_stemma_add').show();
ce1c5863 48 $('#open_textinfo_edit').show();
cbd23059 49 $('#relatebutton_label').text('View collation and edit relationships');
75354c3a 50 } else {
ce1c5863 51 $('#open_stemma_add').hide();
ce1c5863 52 $('#open_textinfo_edit').hide();
cbd23059 53 $('#relatebutton_label').text('View collation and relationships');
75354c3a 54 }
55
62723740 56 // Then get and load the actual content.
98a45925 57 // TODO: scale #stemma_graph both horizontally and vertically
f6a8db89 58 // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
3f9d7ae5 59 $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
98a45925 60 // Add the scalar data
75354c3a 61 selectedTextInfo = textdata;
62 load_textinfo();
63378fe0 63 // Add the stemma(ta)
98a45925 64 stemmata = textdata.stemmata;
65 if( stemmata.length ) {
66 selectedStemmaID = 0;
65a0c9c6 67 } else {
57e3a008 68 selectedStemmaID = -1;
65a0c9c6 69 }
63378fe0 70 load_stemma( selectedStemmaID, editable );
98a45925 71 // Set up the relationship mapper button
3f9d7ae5 72 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
38627d20 73 // Set up the download button
74 $('#dl_tradition').attr( 'href', _get_url([ "download", textid ]) );
75 $('#dl_tradition').attr( 'download', selectedTextInfo.name + '.xml' );
98a45925 76 });
77}
78
3f9d7ae5 79// Load the metadata about a tradition into the appropriate div.
75354c3a 80function load_textinfo() {
81 $('#textinfo_waitbox').hide();
82 $('#textinfo_load_status').empty();
83 $('#textinfo_container').show();
84 $('.texttitle').empty().append( selectedTextInfo.name );
85 // Witnesses
86 $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
87 $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
88 // Who the owner is
89 $('#owner_id').empty().append('no one');
90 if( selectedTextInfo.owner ) {
897a22fc 91 var owneremail = selectedTextInfo.owner;
92 var chop = owneremail.indexOf( '@' );
93 if( chop > -1 ) {
94 owneremail = owneremail.substr( 0, chop + 1 ) + '...';
95 }
96 $('#owner_id').empty().append( owneremail );
75354c3a 97 }
98 // Whether or not it is public
99 $('#not_public').empty();
100 if( selectedTextInfo['public'] == false ) {
101 $('#not_public').append('NOT ');
102 }
103 // What language setting it has, if any
104 $('#marked_language').empty().append('no language set');
105 if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
106 $('#marked_language').empty().append( selectedTextInfo.language );
107 }
108}
109
3f9d7ae5 110// Enable / disable the appropriate buttons for paging through the stemma.
63378fe0 111function show_stemmapager ( editable ) {
bf81fb57 112 $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
113 $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
65a0c9c6 114 if( selectedStemmaID > 0 ) {
115 $('.pager_left_button').click( function () {
63378fe0 116 load_stemma( selectedStemmaID - 1, editable );
bf81fb57 117 }).removeClass( 'greyed_out' );
65a0c9c6 118 }
119 if( selectedStemmaID + 1 < stemmata.length ) {
120 $('.pager_right_button').click( function () {
63378fe0 121 load_stemma( selectedStemmaID + 1, editable );
bf81fb57 122 }).removeClass( 'greyed_out' );
65a0c9c6 123 }
124}
125
3f9d7ae5 126// Load a given stemma SVG into the stemmagraph box.
63378fe0 127function load_stemma( idx, editable ) {
65a0c9c6 128 // Load the stemma at idx
129 selectedStemmaID = idx;
63378fe0 130 show_stemmapager( editable );
131 $('#open_stemma_edit').hide();
132 $('#run_stexaminer').hide();
133 $('#stemma_identifier').empty();
98a45925 134 if( idx > -1 ) {
63378fe0 135 // Load the stemma and its properties
ec2f89ff 136 var stemmadata = stemmata[idx];
63378fe0 137 if( editable ) {
138 $('#open_stemma_edit').show();
139 }
140 if( stemmadata.directed ) {
141 // Stexaminer submit action
142 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
143 $('#run_stexaminer').attr( 'action', stexpath );
144 $('#run_stexaminer').show();
145 }
146 loadSVG( stemmadata.svg );
147 $('#stemma_identifier').text( stemmadata.name );
40803b80 148 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
98a45925 149 }
5ba6c2b4 150}
75354c3a 151
bd3ccd15 152// Load the SVG we are given
153function loadSVG(svgData) {
154 var svgElement = $('#stemma_graph');
155
156 $(svgElement).svg('destroy');
157
158 $(svgElement).svg({
159 loadURL: svgData,
160 onLoad : function () {
161 var theSVG = svgElement.find('svg');
162 var svgoffset = theSVG.offset();
bd3ccd15 163 var browseroffset = 1;
23f8bfc2 164 // Firefox needs a different offset, stupidly enough
bd3ccd15 165 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
23f8bfc2 166 browseroffset = 3; // works for tall images
167 // ...but if the SVG is wider than it is tall, Firefox treats
168 // the top as being the top of the graph, loaded into the middle
169 // of the canvas, but then the margin at the top of the canvas
170 // extends upward. So we have to find the actual top of the canvas
171 // and correct for *that* instead.
172 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
173 if( vbdim.height < vbdim.width ) {
174 var vbscale = svgElement.width() / vbdim.width;
175 var vbrealheight = vbdim.height * vbscale;
176 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
177 }
bd3ccd15 178 }
179 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
bd3ccd15 180 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
181 }
182 });
183}
184
3f9d7ae5 185// General-purpose error-handling function.
186// TODO make sure this gets used throughout, where appropriate.
75354c3a 187function display_error( jqXHR, el ) {
ce1c5863 188 var errmsg;
189 if( jqXHR.responseText == "" ) {
190 errmsg = "perhaps the server went down?"
75354c3a 191 } else {
ce1c5863 192 var errobj;
193 try {
194 errobj = jQuery.parseJSON( jqXHR.responseText );
195 errmsg = errobj.error;
196 } catch ( parse_err ) {
197 errmsg = "something went wrong on the server."
198 }
75354c3a 199 }
ce1c5863 200 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
75354c3a 201 $(el).empty().append( msghtml ).show();
3f9d7ae5 202}
203
e0b90236 204// Event to enable the upload button when a file has been selected
205function file_selected( e ) {
206 if( e.files.length == 1 ) {
207 $('#upload_button').button('enable');
ab0d1218 208 $('#new_file_name_container').html( '<span id="new_file_name">' + e.files[0].name + '</span>' );
e0b90236 209 } else {
210 $('#upload_button').button('disable');
ab0d1218 211 $('#new_file_name_container').html( '(Use \'pick file\' to select a tradition file to upload.)' );
e0b90236 212 }
213}
214
2ece58b3 215// Implement our own AJAX method that uses the features of XMLHttpRequest2
216// but try to let it have a similar interface to jquery.post
217// The data var needs to be a FormData() object.
218// The callback will be given a single argument, which is the response data
219// of the given type.
220
221function post_xhr2( url, data, cb, type ) {
222 if( !type ) {
223 type = 'json';
224 }
225 var xhr = new XMLHttpRequest();
226 // Set the expected response type
227 if( type === 'data' ) {
228 xhr.responseType = 'blob';
229 } else if( type === 'xml' ) {
230 xhr.responseType = 'document';
231 }
232 // Post the form
233 // Gin up an AJAX settings object
234 $.ajaxSetup({ url: url, type: 'POST' });
235 xhr.open( 'POST', url, true );
236 // Handle the results
237 xhr.onload = function( e ) {
238 // Get the response and parse it
239 // Call the callback with the response, whatever it was
240 var xhrs = e.target;
241 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
242 var resp;
243 if( type === 'json' ) {
244 resp = $.parseJSON( xhrs.responseText );
245 } else if ( type === 'xml' ) {
246 resp = xhrs.responseXML;
247 } else if ( type === 'text' ) {
248 resp = xhrs.responseText;
249 } else {
250 resp = xhrs.response;
251 }
252 cb( resp );
253 } else {
254 // Trigger the ajaxError...
255 _trigger_ajaxerror( e );
256 }
257 };
258 xhr.onerror = _trigger_ajaxerror;
259 xhr.onabort = _trigger_ajaxerror;
260 xhr.send( data );
261}
262
263function _trigger_ajaxerror( e ) {
264 var xhr = e.target;
265 var thrown = xhr.statusText || 'Request error';
266 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
267}
268
e0b90236 269function upload_new () {
270 // Serialize the upload form, get the file and attach it to the request,
271 // POST the lot and handle the response.
272 var newfile = $('#new_file').get(0).files[0];
273 var reader = new FileReader();
274 reader.onload = function( evt ) {
2ece58b3 275 var data = new FormData();
276 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
277 data.append( o.name, o.value );
278 });
279 data.append( 'file', newfile );
e0b90236 280 var upload_url = _get_url([ 'newtradition' ]);
2ece58b3 281 post_xhr2( upload_url, data, function( ret ) {
e0b90236 282 if( ret.id ) {
283 $('#upload-collation-dialog').dialog('close');
284 refreshDirectory();
285 loadTradition( ret.id, ret.name, 1 );
286 } else if( ret.error ) {
287 $('#upload_status').empty().append(
288 $('<span>').attr('class', 'error').append( ret.error ) );
289 }
2ece58b3 290 }, 'json' );
e0b90236 291 };
292 reader.onerror = function( evt ) {
293 var err_resp = 'File read error';
294 if( e.name == 'NotFoundError' ) {
295 err_resp = 'File not found';
296 } else if ( e.name == 'NotReadableError' ) {
297 err_resp == 'File unreadable - is it yours?';
298 } else if ( e.name == 'EncodingError' ) {
299 err_resp == 'File cannot be encoded - is it too long?';
300 } else if ( e.name == 'SecurityError' ) {
301 err_resp == 'File read security error';
302 }
303 // Fake a jqXHR object that we can pass to our generic error handler.
304 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
305 display_error( jqxhr, $('#upload_status') );
306 $('#upload_button').button('disable');
307 }
308
309 reader.readAsBinaryString( newfile );
3f9d7ae5 310}
311
312// Utility function to neatly construct an application URL
313function _get_url( els ) {
314 return basepath + els.join('/');
315}
316
bd3ccd15 317
3f9d7ae5 318$(document).ready( function() {
50778a5d 319 // See if we have the browser functionality we need
320 // TODO Also think of a test for SVG readiness
7c25980f 321 if( !!window.FileReader && !!window.File ) {
50778a5d 322 $('#compatibility_check').empty();
323 }
324
3f9d7ae5 325 // call out to load the directory div
326 $('#textinfo_container').hide();
327 $('#textinfo_waitbox').hide();
328 refreshDirectory();
329
330 // Set up the textinfo edit dialog
331 $('#textinfo-edit-dialog').dialog({
332 autoOpen: false,
333 height: 200,
334 width: 300,
335 modal: true,
336 buttons: {
337 Save: function (evt) {
338 $("#edit_textinfo_status").empty();
339 $(evt.target).button("disable");
340 var requrl = _get_url([ "textinfo", selectedTextID ]);
341 var reqparam = $('#edit_textinfo').serialize();
342 $.post( requrl, reqparam, function (data) {
343 // Reload the selected text fields
344 selectedTextInfo = data;
345 load_textinfo();
346 // Reenable the button and close the form
347 $(evt.target).button("enable");
348 $('#textinfo-edit-dialog').dialog('close');
349 }, 'json' );
350 },
351 Cancel: function() {
352 $('#textinfo-edit-dialog').dialog('close');
353 }
354 },
355 open: function() {
356 $("#edit_textinfo_status").empty();
357 // Populate the form fields with the current values
358 // edit_(name, language, public, owner)
359 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
360 var fname = '#edit_' + k;
361 // Special case: language Default is basically language null
362 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
363 $(fname).val( "" );
364 } else {
365 $(fname).val( selectedTextInfo[k] );
366 }
367 });
368 if( selectedTextInfo['public'] == true ) {
369 $('#edit_public').attr('checked','true');
370 } else {
371 $('#edit_public').removeAttr('checked');
372 }
373 },
374 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
375 $(event.target).parent().find('.ui-button').button("enable");
376 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
377 && ajaxSettings.type == 'POST' ) {
378 display_error( jqXHR, $("#edit_textinfo_status") );
379 }
380 });
381
382
383 // Set up the stemma editor dialog
384 $('#stemma-edit-dialog').dialog({
385 autoOpen: false,
386 height: 700,
387 width: 600,
388 modal: true,
389 buttons: {
390 Save: function (evt) {
391 $("#edit_stemma_status").empty();
392 $(evt.target).button("disable");
393 var stemmaseq = $('#stemmaseq').val();
394 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
395 var reqparam = { 'dot': $('#dot_field').val() };
396 // TODO We need to stash the literal SVG string in stemmata
397 // somehow. Implement accept header on server side to decide
398 // whether to send application/json or application/xml?
399 $.post( requrl, reqparam, function (data) {
400 // We received a stemma SVG string in return.
401 // Update the current stemma sequence number
402 selectedStemmaID = data.stemmaid;
be536c89 403 delete data.stemmaid;
404 // Stash the answer in the appropriate spot in our stemma array
405 stemmata[selectedStemmaID] = data;
3f9d7ae5 406 // Display the new stemma
63378fe0 407 load_stemma( selectedStemmaID, true );
3f9d7ae5 408 // Reenable the button and close the form
409 $(evt.target).button("enable");
410 $('#stemma-edit-dialog').dialog('close');
411 }, 'json' );
412 },
413 Cancel: function() {
414 $('#stemma-edit-dialog').dialog('close');
415 }
416 },
417 open: function(evt) {
418 $("#edit_stemma_status").empty();
419 var stemmaseq = $('#stemmaseq').val();
420 if( stemmaseq == 'n' ) {
421 // If we are creating a new stemma, populate the textarea with a
422 // bare digraph.
423 $(evt.target).dialog('option', 'title', 'Add a new stemma')
424 $('#dot_field').val( "digraph stemma {\n\n}" );
425 } else {
426 // If we are editing a stemma, grab its stemmadot and populate the
427 // textarea with that.
428 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
429 $('#dot_field').val( 'Loading, please wait...' );
430 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
431 $.getJSON( doturl, function (data) {
432 // Re-insert the line breaks
433 var dotstring = data.dot.replace(/\|n/gm, "\n");
434 $('#dot_field').val( dotstring );
435 });
436 }
437 },
438 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
439 $(event.target).parent().find('.ui-button').button("enable");
440 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
441 && ajaxSettings.type == 'POST' ) {
442 display_error( jqXHR, $("#edit_stemma_status") );
443 }
444 });
445
446 $('#upload-collation-dialog').dialog({
447 autoOpen: false,
e0b90236 448 height: 360,
3f9d7ae5 449 width: 480,
450 modal: true,
451 buttons: {
3f9d7ae5 452 upload: {
453 text: 'Upload',
454 id: 'upload_button',
455 click: function() {
456 $('#upload_status').empty();
e0b90236 457 $('#upload_button').button("disable");
458 upload_new();
3f9d7ae5 459 }
460 },
ab0d1218 461 pick_file: {
462 text: 'Pick File',
463 id: 'pick_file_button',
464 click: function() {
465 $('#new_file').click();
466 }
467 },
3f9d7ae5 468 Cancel: function() {
469 $('#upload-collation-dialog').dialog('close');
470 }
471 },
e0b90236 472 open: function() {
473 // Set the upload button to its correct state based on
474 // whether a file is loaded
475 file_selected( $('#new_file').get(0) );
2ece58b3 476 $('#upload_status').empty();
3f9d7ae5 477 }
e0b90236 478 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
479 // Reset button state
480 file_selected( $('#new_file').get(0) );
481 // Display error message if applicable
482 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
483 && ajaxSettings.type == 'POST' ) {
484 display_error( jqXHR, $("#upload_status") );
485 }
486 });;
3f9d7ae5 487
488 $('#stemma_graph').mousedown( function(evt) {
489 evt.stopPropagation();
490 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
491 $('body').mousemove( function(evt) {
492 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
493 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
494 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
495 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
496 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
497 var g = $('g.graph', svg_root).get(0);
498 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
499 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
500 g.setAttribute( 'transform', new_transform );
501 evt.returnValue = false;
502 evt.preventDefault();
503 return false;
504 });
505 $('body').mouseup( function(evt) {
506 $('body').unbind('mousemove');
507 $('body').unbind('mouseup');
508 });
509 });
510
511 $('#stemma_graph').mousewheel(function (event, delta) {
512 event.returnValue = false;
513 event.preventDefault();
514 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
515 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
516 if( delta < -9 ) { delta = -9 };
517 var z = 1 + delta/10;
518 z = delta > 0 ? 1 : -1;
519 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
520 var g = $('g.graph', svg_root).get(0);
521 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
522 var scaleLevel = z/10;
523 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
524 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
525 g.setAttribute( 'transform', new_transform );
526 }
527 });
528
529});