1 // Global state variables
4 var selectedStemmaID = -1;
7 // Load the names of the appropriate traditions into the directory div.
8 function 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);
17 if( textOnLoad != "" ) {
18 // Call the click callback for the relevant text, if it is
20 $('#'+textOnLoad).click();
28 // Load a tradition with its information and stemmata into the tradition
29 // view pane. Calls load_textinfo.
30 function loadTradition( textid, textname, editable ) {
31 selectedTextID = textid;
32 // First insert the placeholder image and register an error handler
33 $('#textinfo_load_status').empty();
34 $('#stemma_graph').empty();
35 $('#textinfo_waitbox').show();
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") );
45 // Hide the functionality that is irrelevant
47 $('#open_stemma_add').show();
48 $('#open_stemma_edit').show();
49 $('#open_textinfo_edit').show();
51 $('#open_stemma_add').hide();
52 $('#open_stemma_edit').hide();
53 $('#open_textinfo_edit').hide();
56 // Then get and load the actual content.
57 // TODO: scale #stemma_graph both horizontally and vertically
58 // TODO: load svgs from SVG.Jquery (to make scaling react in Safari)
59 $.getJSON( _get_url([ "textinfo", textid ]), function (textdata) {
60 // Add the scalar data
61 selectedTextInfo = textdata;
63 // Add the stemma(ta) and set up the stexaminer button
64 stemmata = textdata.stemmata;
65 if( stemmata.length ) {
67 $('#run_stexaminer').show();
69 selectedStemmaID = -1;
70 $('#open_stemma_edit').hide();
71 $('#run_stexaminer').hide();
73 load_stemma( selectedStemmaID );
74 // Set up the relationship mapper button
75 $('#run_relater').attr( 'action', _get_url([ "relation", textid ]) );
79 // Load the metadata about a tradition into the appropriate div.
80 function load_textinfo() {
81 $('#textinfo_waitbox').hide();
82 $('#textinfo_load_status').empty();
83 $('#textinfo_container').show();
84 $('.texttitle').empty().append( selectedTextInfo.name );
86 $('#witness_num').empty().append( selectedTextInfo.witnesses.size );
87 $('#witness_list').empty().append( selectedTextInfo.witnesses.join( ', ' ) );
89 $('#owner_id').empty().append('no one');
90 if( selectedTextInfo.owner ) {
91 $('#owner_id').empty().append( selectedTextInfo.owner );
93 // Whether or not it is public
94 $('#not_public').empty();
95 if( selectedTextInfo['public'] == false ) {
96 $('#not_public').append('NOT ');
98 // What language setting it has, if any
99 $('#marked_language').empty().append('no language set');
100 if( selectedTextInfo.language && selectedTextInfo.language != 'Default' ) {
101 $('#marked_language').empty().append( selectedTextInfo.language );
105 // Enable / disable the appropriate buttons for paging through the stemma.
106 function show_stemmapager () {
107 $('.pager_left_button').unbind('click').addClass( 'greyed_out' );
108 $('.pager_right_button').unbind('click').addClass( 'greyed_out' );
109 if( selectedStemmaID > 0 ) {
110 $('.pager_left_button').click( function () {
111 load_stemma( selectedStemmaID - 1 );
112 }).removeClass( 'greyed_out' );
114 if( selectedStemmaID + 1 < stemmata.length ) {
115 $('.pager_right_button').click( function () {
116 load_stemma( selectedStemmaID + 1 );
117 }).removeClass( 'greyed_out' );
121 // Load a given stemma SVG into the stemmagraph box.
122 function load_stemma( idx ) {
123 // Load the stemma at idx
124 selectedStemmaID = idx;
127 loadSVG( stemmata[idx] );
128 // Stexaminer submit action
129 var stexpath = _get_url([ "stexaminer", selectedTextID, idx ]);
130 $('#run_stexaminer').attr( 'action', stexpath );
131 setTimeout( 'start_element_height = $("#stemma_graph .node")[0].getBBox().height;', 500 );
135 // Load the SVG we are given
136 function loadSVG(svgData) {
137 var svgElement = $('#stemma_graph');
139 $(svgElement).svg('destroy');
143 onLoad : function () {
144 var theSVG = svgElement.find('svg');
145 var svgoffset = theSVG.offset();
146 var browseroffset = 1;
147 // Firefox needs a different offset, stupidly enough
148 if( navigator.userAgent.indexOf('Firefox') > -1 ) {
149 browseroffset = 3; // works for tall images
150 // ...but if the SVG is wider than it is tall, Firefox treats
151 // the top as being the top of the graph, loaded into the middle
152 // of the canvas, but then the margin at the top of the canvas
153 // extends upward. So we have to find the actual top of the canvas
154 // and correct for *that* instead.
155 var vbdim = svgElement.svg().svg('get').root().viewBox.baseVal;
156 if( vbdim.height < vbdim.width ) {
157 var vbscale = svgElement.width() / vbdim.width;
158 var vbrealheight = vbdim.height * vbscale;
159 browseroffset = 3 + ( svgElement.height() - vbrealheight ) / 2;
162 var topoffset = theSVG.position().top - svgElement.position().top - browseroffset;
163 theSVG.offset({ top: svgoffset.top - topoffset, left: svgoffset.left });
168 // General-purpose error-handling function.
169 // TODO make sure this gets used throughout, where appropriate.
170 function display_error( jqXHR, el ) {
172 if( jqXHR.responseText == "" ) {
173 errmsg = "perhaps the server went down?"
177 errobj = jQuery.parseJSON( jqXHR.responseText );
178 errmsg = errobj.error;
179 } catch ( parse_err ) {
180 errmsg = "something went wrong on the server."
183 var msghtml = $('<span>').attr('class', 'error').text( "An error occurred: " + errmsg );
184 $(el).empty().append( msghtml ).show();
187 // Event to enable the upload button when a file has been selected
188 function file_selected( e ) {
189 if( e.files.length == 1 ) {
190 $('#upload_button').button('enable');
192 $('#upload_button').button('disable');
196 // Implement our own AJAX method that uses the features of XMLHttpRequest2
197 // but try to let it have a similar interface to jquery.post
198 // The data var needs to be a FormData() object.
199 // The callback will be given a single argument, which is the response data
200 // of the given type.
202 function post_xhr2( url, data, cb, type ) {
206 var xhr = new XMLHttpRequest();
207 // Set the expected response type
208 if( type === 'data' ) {
209 xhr.responseType = 'blob';
210 } else if( type === 'xml' ) {
211 xhr.responseType = 'document';
214 // Gin up an AJAX settings object
215 $.ajaxSetup({ url: url, type: 'POST' });
216 xhr.open( 'POST', url, true );
217 // Handle the results
218 xhr.onload = function( e ) {
219 // Get the response and parse it
220 // Call the callback with the response, whatever it was
222 if( xhrs.status > 199 && xhrs.status < 300 ) { // Success
224 if( type === 'json' ) {
225 resp = $.parseJSON( xhrs.responseText );
226 } else if ( type === 'xml' ) {
227 resp = xhrs.responseXML;
228 } else if ( type === 'text' ) {
229 resp = xhrs.responseText;
231 resp = xhrs.response;
235 // Trigger the ajaxError...
236 _trigger_ajaxerror( e );
239 xhr.onerror = _trigger_ajaxerror;
240 xhr.onabort = _trigger_ajaxerror;
244 function _trigger_ajaxerror( e ) {
246 var thrown = xhr.statusText || 'Request error';
247 jQuery.event.trigger( 'ajaxError', [ xhr, $.ajaxSettings, thrown ]);
250 function upload_new () {
251 // Serialize the upload form, get the file and attach it to the request,
252 // POST the lot and handle the response.
253 var newfile = $('#new_file').get(0).files[0];
254 var reader = new FileReader();
255 reader.onload = function( evt ) {
256 var data = new FormData();
257 $.each( $('#new_tradition').serializeArray(), function( i, o ) {
258 data.append( o.name, o.value );
260 data.append( 'file', newfile );
261 var upload_url = _get_url([ 'newtradition' ]);
262 post_xhr2( upload_url, data, function( ret ) {
264 $('#upload-collation-dialog').dialog('close');
266 loadTradition( ret.id, ret.name, 1 );
267 } else if( ret.error ) {
268 $('#upload_status').empty().append(
269 $('<span>').attr('class', 'error').append( ret.error ) );
273 reader.onerror = function( evt ) {
274 var err_resp = 'File read error';
275 if( e.name == 'NotFoundError' ) {
276 err_resp = 'File not found';
277 } else if ( e.name == 'NotReadableError' ) {
278 err_resp == 'File unreadable - is it yours?';
279 } else if ( e.name == 'EncodingError' ) {
280 err_resp == 'File cannot be encoded - is it too long?';
281 } else if ( e.name == 'SecurityError' ) {
282 err_resp == 'File read security error';
284 // Fake a jqXHR object that we can pass to our generic error handler.
285 var jqxhr = { responseText: '{error:"' + err_resp + '"}' };
286 display_error( jqxhr, $('#upload_status') );
287 $('#upload_button').button('disable');
290 reader.readAsBinaryString( newfile );
293 // Utility function to neatly construct an application URL
294 function _get_url( els ) {
295 return basepath + els.join('/');
299 $(document).ready( function() {
300 // See if we have the browser functionality we need
301 // TODO Also think of a test for SVG readiness
302 if( !!window.FileReader && !!window.File ) {
303 $('#compatibility_check').empty();
306 // call out to load the directory div
307 $('#textinfo_container').hide();
308 $('#textinfo_waitbox').hide();
311 // Set up the textinfo edit dialog
312 $('#textinfo-edit-dialog').dialog({
318 Save: function (evt) {
319 $("#edit_textinfo_status").empty();
320 $(evt.target).button("disable");
321 var requrl = _get_url([ "textinfo", selectedTextID ]);
322 var reqparam = $('#edit_textinfo').serialize();
323 $.post( requrl, reqparam, function (data) {
324 // Reload the selected text fields
325 selectedTextInfo = data;
327 // Reenable the button and close the form
328 $(evt.target).button("enable");
329 $('#textinfo-edit-dialog').dialog('close');
333 $('#textinfo-edit-dialog').dialog('close');
337 $("#edit_textinfo_status").empty();
338 // Populate the form fields with the current values
339 // edit_(name, language, public, owner)
340 $.each([ 'name', 'language', 'owner' ], function( idx, k ) {
341 var fname = '#edit_' + k;
342 // Special case: language Default is basically language null
343 if( k == 'language' && selectedTextInfo[k] == 'Default' ) {
346 $(fname).val( selectedTextInfo[k] );
349 if( selectedTextInfo['public'] == true ) {
350 $('#edit_public').attr('checked','true');
352 $('#edit_public').removeAttr('checked');
355 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
356 $(event.target).parent().find('.ui-button').button("enable");
357 if( ajaxSettings.url.indexOf( 'textinfo' ) > -1
358 && ajaxSettings.type == 'POST' ) {
359 display_error( jqXHR, $("#edit_textinfo_status") );
364 // Set up the stemma editor dialog
365 $('#stemma-edit-dialog').dialog({
371 Save: function (evt) {
372 $("#edit_stemma_status").empty();
373 $(evt.target).button("disable");
374 var stemmaseq = $('#stemmaseq').val();
375 var requrl = _get_url([ "stemma", selectedTextID, stemmaseq ]);
376 var reqparam = { 'dot': $('#dot_field').val() };
377 // TODO We need to stash the literal SVG string in stemmata
378 // somehow. Implement accept header on server side to decide
379 // whether to send application/json or application/xml?
380 $.post( requrl, reqparam, function (data) {
381 // We received a stemma SVG string in return.
382 // Update the current stemma sequence number
383 selectedStemmaID = data.stemmaid;
384 // Stash the answer in our SVG array
385 stemmata[selectedStemmaID] = data.stemmasvg;
386 // Display the new stemma
387 load_stemma( selectedStemmaID );
388 // Reenable the button and close the form
389 $(evt.target).button("enable");
390 $('#stemma-edit-dialog').dialog('close');
394 $('#stemma-edit-dialog').dialog('close');
397 open: function(evt) {
398 $("#edit_stemma_status").empty();
399 var stemmaseq = $('#stemmaseq').val();
400 if( stemmaseq == 'n' ) {
401 // If we are creating a new stemma, populate the textarea with a
403 $(evt.target).dialog('option', 'title', 'Add a new stemma')
404 $('#dot_field').val( "digraph stemma {\n\n}" );
406 // If we are editing a stemma, grab its stemmadot and populate the
407 // textarea with that.
408 $(evt.target).dialog('option', 'title', 'Edit selected stemma')
409 $('#dot_field').val( 'Loading, please wait...' );
410 var doturl = _get_url([ "stemmadot", selectedTextID, stemmaseq ]);
411 $.getJSON( doturl, function (data) {
412 // Re-insert the line breaks
413 var dotstring = data.dot.replace(/\|n/gm, "\n");
414 $('#dot_field').val( dotstring );
418 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
419 $(event.target).parent().find('.ui-button').button("enable");
420 if( ajaxSettings.url.indexOf( 'stemma' ) > -1
421 && ajaxSettings.type == 'POST' ) {
422 display_error( jqXHR, $("#edit_stemma_status") );
426 $('#upload-collation-dialog').dialog({
436 $('#upload_status').empty();
437 $('#upload_button').button("disable");
442 $('#upload-collation-dialog').dialog('close');
446 // Set the upload button to its correct state based on
447 // whether a file is loaded
448 file_selected( $('#new_file').get(0) );
449 $('#upload_status').empty();
451 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
452 // Reset button state
453 file_selected( $('#new_file').get(0) );
454 // Display error message if applicable
455 if( ajaxSettings.url.indexOf( 'newtradition' ) > -1
456 && ajaxSettings.type == 'POST' ) {
457 display_error( jqXHR, $("#upload_status") );
461 $('#stemma_graph').mousedown( function(evt) {
462 evt.stopPropagation();
463 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
464 $('body').mousemove( function(evt) {
465 mouse_scale = 1; // for now, was: mouse_scale = svg_root_element.getScreenCTM().a;
466 dx = (evt.clientX - $('#stemma_graph').data( 'mousedown_xy' )[0]) / mouse_scale;
467 dy = (evt.clientY - $('#stemma_graph').data( 'mousedown_xy' )[1]) / mouse_scale;
468 $('#stemma_graph').data( 'mousedown_xy', [evt.clientX, evt.clientY] );
469 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
470 var g = $('g.graph', svg_root).get(0);
471 current_translate = g.getAttribute( 'transform' ).split(/translate\(/)[1].split(')',1)[0].split(' ');
472 new_transform = g.getAttribute( 'transform' ).replace( /translate\([^\)]*\)/, 'translate(' + (parseFloat(current_translate[0]) + dx) + ' ' + (parseFloat(current_translate[1]) + dy) + ')' );
473 g.setAttribute( 'transform', new_transform );
474 evt.returnValue = false;
475 evt.preventDefault();
478 $('body').mouseup( function(evt) {
479 $('body').unbind('mousemove');
480 $('body').unbind('mouseup');
484 $('#stemma_graph').mousewheel(function (event, delta) {
485 event.returnValue = false;
486 event.preventDefault();
487 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
488 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
489 if( delta < -9 ) { delta = -9 };
490 var z = 1 + delta/10;
491 z = delta > 0 ? 1 : -1;
492 var svg_root = $('#stemma_graph svg').svg().svg('get').root();
493 var g = $('g.graph', svg_root).get(0);
494 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 1000))) {
495 var scaleLevel = z/10;
496 current_scale = parseFloat( g.getAttribute( 'transform' ).split(/scale\(/)[1].split(')',1)[0].split(' ')[0] );
497 new_transform = g.getAttribute( 'transform' ).replace( /scale\([^\)]*\)/, 'scale(' + (current_scale + scaleLevel) + ')' );
498 g.setAttribute( 'transform', new_transform );