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