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