add is_significant attribute to relationships. Closes #33
[scpubgit/stemmaweb.git] / root / js / relationship.js
CommitLineData
76f05423 1var MARGIN=30;
2var svg_root = null;
3var svg_root_element = null;
4var start_element_height = 0;
5var reltypes = {};
5f15640c 6var readingdata = {};
76f05423 7
a471cb0f 8jQuery.removeFromArray = function(value, arr) {
9 return jQuery.grep(arr, function(elem, index) {
10 return elem !== value;
11 });
12};
13
a84ca4de 14function arrayUnique(array) {
15 var a = array.concat();
16 for(var i=0; i<a.length; ++i) {
17 for(var j=i+1; j<a.length; ++j) {
18 if(a[i] === a[j])
19 a.splice(j--, 1);
20 }
21 }
22 return a;
23};
24
5f15640c 25function getTextURL( which ) {
3f9d7ae5 26 return basepath + textid + '/' + which;
5f15640c 27}
28
29function getReadingURL( reading_id ) {
3f9d7ae5 30 return basepath + textid + '/reading/' + reading_id;
b28e606e 31}
32
45ee3b96 33// Make an XML ID into a valid selector
34function jq(myid) {
35 return '#' + myid.replace(/(:|\.)/g,'\\$1');
36}
37
065c7cf2 38// Actions for opening the reading panel
39function node_dblclick_listener( evt ) {
40 // Open the reading dialogue for the given node.
41 // First get the reading info
42 var reading_id = $(this).attr('id');
43 var reading_info = readingdata[reading_id];
44 // and then populate the dialog box with it.
45 // Set the easy properties first
46 $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
47 $('#reading_id').val( reading_id );
798fa939 48 toggle_checkbox( $('#reading_is_nonsense'), reading_info['is_nonsense'] );
49 toggle_checkbox( $('#reading_grammar_invalid'), reading_info['grammar_invalid'] );
065c7cf2 50 // Use .text as a backup for .normal_form
51 var normal_form = reading_info['normal_form'];
52 if( !normal_form ) {
53 normal_form = reading_info['text'];
54 }
55 var nfboxsize = 10;
56 if( normal_form.length > 9 ) {
57 nfboxsize = normal_form.length + 1;
58 }
59 $('#reading_normal_form').attr( 'size', nfboxsize )
60 $('#reading_normal_form').val( normal_form );
61 // Now do the morphological properties.
0dcdd5ec 62 morphology_form( reading_info['lexemes'] );
065c7cf2 63 // and then open the dialog.
0dcdd5ec 64 $('#reading-form').dialog("open");
65}
66
798fa939 67function toggle_checkbox( box, value ) {
68 if( value == null ) {
69 value = false;
70 }
71 box.attr('checked', value );
72}
73
0dcdd5ec 74function morphology_form ( lexlist ) {
487674b9 75 if( lexlist.length ) {
76 $('#morph_outer').show();
77 $('#morphology').empty();
78 $.each( lexlist, function( idx, lex ) {
79 var morphoptions = [];
80 if( 'wordform_matchlist' in lex ) {
81 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
82 var tagstr = stringify_wordform( tag );
83 morphoptions.push( tagstr );
84 });
85 }
86 var formtag = 'morphology_' + idx;
87 var formstr = '';
88 if( 'form' in lex ) {
89 formstr = stringify_wordform( lex['form'] );
90 }
91 var form_morph_elements = morph_elements(
92 formtag, lex['string'], formstr, morphoptions );
93 $.each( form_morph_elements, function( idx, el ) {
94 $('#morphology').append( el );
08f8443a 95 });
065c7cf2 96 });
487674b9 97 } else {
98 $('#morph_outer').hide();
99 }
065c7cf2 100}
101
102function stringify_wordform ( tag ) {
08f8443a 103 if( tag ) {
104 var elements = tag.split(' // ');
105 return elements[1] + ' // ' + elements[2];
106 }
107 return ''
065c7cf2 108}
109
d1132306 110function morph_elements ( formtag, formtxt, currform, morphoptions ) {
111 var clicktag = '(Click to select)';
112 if ( !currform ) {
113 currform = clicktag;
114 }
065c7cf2 115 var formlabel = $('<label/>').attr( 'id', 'label_' + formtag ).attr(
d1132306 116 'for', 'reading_' + formtag ).text( formtxt + ': ' );
065c7cf2 117 var forminput = $('<input/>').attr( 'id', 'reading_' + formtag ).attr(
0dcdd5ec 118 'name', 'reading_' + formtag ).attr( 'size', '50' ).attr(
119 'class', 'reading_morphology' ).val( currform );
d1132306 120 forminput.autocomplete({ source: morphoptions, minLength: 0 });
121 forminput.focus( function() {
122 if( $(this).val() == clicktag ) {
123 $(this).val('');
124 }
125 $(this).autocomplete('search', '')
126 });
065c7cf2 127 var morphel = [ formlabel, forminput, $('<br/>') ];
128 return morphel;
129}
130
4c41c02c 131function color_inactive ( el ) {
132 var reading_id = $(el).parent().attr('id');
133 var reading_info = readingdata[reading_id];
134 // If the reading info has any non-disambiguated lexemes, color it yellow;
135 // otherwise color it green.
136 $(el).attr( {stroke:'green', fill:'#b3f36d'} );
bb3230b1 137 if( reading_info ) {
138 $.each( reading_info['lexemes'], function ( idx, lex ) {
139 if( !lex['is_disambiguated'] || lex['is_disambiguated'] == 0 ) {
140 $(el).attr( {stroke:'orange', fill:'#fee233'} );
141 }
142 });
143 }
4c41c02c 144}
145
997ebe92 146function relemmatize () {
147 // Send the reading for a new lemmatization and reopen the form.
a0a66634 148 $('#relemmatize_pending').show();
997ebe92 149 var reading_id = $('#reading_id').val()
150 ncpath = getReadingURL( reading_id );
151 form_values = {
152 'normal_form': $('#reading_normal_form').val(),
153 'relemmatize': 1 };
154 var jqjson = $.post( ncpath, form_values, function( data ) {
155 // Update the form with the return
156 if( 'id' in data ) {
157 // We got back a good answer. Stash it
158 readingdata[reading_id] = data;
159 // and regenerate the morphology form.
160 morphology_form( data['lexemes'] );
161 } else {
162 alert("Could not relemmatize as requested: " + data['error']);
163 }
a0a66634 164 $('#relemmatize_pending').hide();
997ebe92 165 });
166}
167
065c7cf2 168// Initialize the SVG once it exists
b28e606e 169function svgEnlargementLoaded() {
fc018906 170 //Give some visual evidence that we are working
171 $('#loading_overlay').show();
172 lo_height = $("#enlargement_container").outerHeight();
173 lo_width = $("#enlargement_container").outerWidth();
174 $("#loading_overlay").height( lo_height );
175 $("#loading_overlay").width( lo_width );
176 $("#loading_overlay").offset( $("#enlargement_container").offset() );
177 $("#loading_message").offset(
178 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
179 'left': lo_width / 2 - $("#loading_message").width() / 2 });
30d0ba1e 180 if( editable ) {
181 // Show the update toggle button.
182 $('#update_workspace_button').data('locked', false);
183 $('#update_workspace_button').css('background-position', '0px 44px');
184 }
065c7cf2 185 $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
9529f69c 186 var graph_svg = $('#svgenlargement svg');
187 var svg_g = $('#svgenlargement svg g')[0];
76f05423 188 if (!svg_g) return;
9529f69c 189 svg_root = graph_svg.svg().svg('get').root();
76f05423 190
191 // Find the real root and ignore any text nodes
192 for (i = 0; i < svg_root.childNodes.length; ++i) {
193 if (svg_root.childNodes[i].nodeName != '#text') {
194 svg_root_element = svg_root.childNodes[i];
195 break;
196 }
197 }
198
30d0ba1e 199 //Set viewbox width and height to width and height of $('#svgenlargement svg').
200 //This is essential to make sure zooming and panning works properly.
9529f69c 201 svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
202 svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
203 //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
204 //This is just to create a nice starting enlargement.
205 var initial_svg_height = 250;
206 var scale = initial_svg_height/graph_svg.attr( 'height' );
207 var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
208 var transform = svg_g.getAttribute('transform');
209 var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
210 translate += additional_translate;
211 var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
212 svg_g.setAttribute('transform', transform);
213 //used to calculate min and max zoom level:
4c41c02c 214 start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
e538eccb 215 //some use of call backs to ensure succesive execution
216 add_relations( function() {
217 var rdgpath = getTextURL( 'readings' );
218 $.getJSON( rdgpath, function( data ) {
219 readingdata = data;
220 $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
9231663d 221 $('#loading_overlay').hide();
e538eccb 222 });
e538eccb 223 });
c1add777 224
225 //initialize marquee
226 marquee = new Marquee();
227
6afcd813 228}
229
fc018906 230function add_relations( callback_fn ) {
56e3972e 231 // Add the relationship types to the keymap list
56e3972e 232 $.each( relationship_types, function(index, typedef) {
671c04b1 233 li_elm = $('<li class="key">').css( "border-color",
234 relation_manager.relation_colors[index] ).text(typedef.name);
235 li_elm.append( $('<div>').attr('class', 'key_tip_container').append(
236 $('<div>').attr('class', 'key_tip').text(typedef.description) ) );
cfefd283 237 $('#keymaplist').append( li_elm );
56e3972e 238 });
239 // Now fetch the relationships themselves and add them to the graph
240 var rel_types = $.map( relationship_types, function(t) { return t.name });
241 // Save this list of names to the outer element data so that the relationship
242 // factory can access it
243 $('#keymap').data('relations', rel_types);
5f15640c 244 var textrelpath = getTextURL( 'relationships' );
56e3972e 245 $.getJSON( textrelpath, function(data) {
246 $.each(data, function( index, rel_info ) {
247 var type_index = $.inArray(rel_info.type, rel_types);
51ca18ee 248 var source_found = get_ellipse( rel_info.source_id );
249 var target_found = get_ellipse( rel_info.target_id );
56e3972e 250 if( type_index != -1 && source_found.size() && target_found.size() ) {
51ca18ee 251 var relation = relation_manager.create( rel_info.source_id, rel_info.target_id, type_index );
252 // Save the relationship data too.
253 $.each( rel_info, function( k, v ) {
254 relation.data( k, v );
255 });
30d0ba1e 256 if( editable ) {
51ca18ee 257 var node_obj = get_node_obj(rel_info.source_id);
e538eccb 258 node_obj.set_selectable( false );
30d0ba1e 259 node_obj.ellipse.data( 'node_obj', null );
51ca18ee 260 node_obj = get_node_obj(rel_info.target_id);
e538eccb 261 node_obj.set_selectable( false );
30d0ba1e 262 node_obj.ellipse.data( 'node_obj', null );
263 }
56e3972e 264 }
265 });
266 callback_fn.call();
267 });
b28e606e 268}
269
270function get_ellipse( node_id ) {
45ee3b96 271 return $( jq( node_id ) + ' ellipse');
b28e606e 272}
273
274function get_node_obj( node_id ) {
9529f69c 275 var node_ellipse = get_ellipse( node_id );
276 if( node_ellipse.data( 'node_obj' ) == null ) {
277 node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
278 };
279 return node_ellipse.data( 'node_obj' );
b28e606e 280}
281
b28e606e 282function node_obj(ellipse) {
283 this.ellipse = ellipse;
284 var self = this;
285
286 this.x = 0;
287 this.y = 0;
288 this.dx = 0;
289 this.dy = 0;
290 this.node_elements = node_elements_for(self.ellipse);
22a70299 291
b28e606e 292 this.get_id = function() {
45ee3b96 293 return $(self.ellipse).parent().attr('id')
b28e606e 294 }
295
e538eccb 296 this.set_selectable = function( clickable ) {
297 if( clickable && editable ) {
298 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
299 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
300 $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } );
301 $(self.ellipse).parent().click( function(evt) {
302 evt.stopPropagation();
303 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
304 $('ellipse[fill="#9999ff"]').each( function() {
305 $(this).data( 'node_obj' ).set_draggable( false );
306 } );
307 }
308 self.set_draggable( true )
309 });
310 } else {
311 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
312 self.ellipse.siblings('text').attr('class', '');
313 $(self.ellipse).parent().unbind();
314 $('body').unbind('mousemove');
315 $('body').unbind('mouseup');
316 }
317 }
318
b28e606e 319 this.set_draggable = function( draggable ) {
30d0ba1e 320 if( draggable && editable ) {
e538eccb 321 $(self.ellipse).attr( {stroke:'black', fill:'#9999ff'} );
05485bfd 322 $(self.ellipse).parent().mousedown( this.mousedown_listener );
e538eccb 323 $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' );
05485bfd 324 self.ellipse.siblings('text').attr('class', 'noselect draggable');
b28e606e 325 } else {
e538eccb 326 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
05485bfd 327 self.ellipse.siblings('text').attr('class', '');
e538eccb 328 $(self.ellipse).parent().unbind( 'mousedown ');
329 $(self.ellipse).parent().mousedown( function(evt) { evt.stopPropagation() } );
330 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
b28e606e 331 }
332 }
333
334 this.mousedown_listener = function(evt) {
335 evt.stopPropagation();
336 self.x = evt.clientX;
337 self.y = evt.clientY;
338 $('body').mousemove( self.mousemove_listener );
339 $('body').mouseup( self.mouseup_listener );
05485bfd 340 $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
e538eccb 341 self.ellipse.attr( 'fill', '#6b6bb2' );
b28e606e 342 first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
343 if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
344 }
345
346 this.mousemove_listener = function(evt) {
9529f69c 347 self.dx = (evt.clientX - self.x) / mouse_scale;
348 self.dy = (evt.clientY - self.y) / mouse_scale;
b28e606e 349 self.move_elements();
05485bfd 350 evt.returnValue = false;
351 evt.preventDefault();
352 return false;
b28e606e 353 }
354
355 this.mouseup_listener = function(evt) {
356 if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
45ee3b96 357 var source_node_id = $(self.ellipse).parent().attr('id');
05485bfd 358 var source_node_text = self.ellipse.siblings('text').text();
45ee3b96 359 var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
05485bfd 360 var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
b28e606e 361 $('#source_node_id').val( source_node_id );
05485bfd 362 $('#source_node_text').val( source_node_text );
51ca18ee 363 $('.rel_rdg_a').text( "'" + source_node_text + "'" );
b28e606e 364 $('#target_node_id').val( target_node_id );
05485bfd 365 $('#target_node_text').val( target_node_text );
51ca18ee 366 $('.rel_rdg_b').text( "'" + target_node_text + "'" );
b28e606e 367 $('#dialog-form').dialog( 'open' );
368 };
369 $('body').unbind('mousemove');
370 $('body').unbind('mouseup');
e538eccb 371 self.ellipse.attr( 'fill', '#9999ff' );
9529f69c 372 self.reset_elements();
b28e606e 373 }
f2fb96fc 374
b28e606e 375 this.cpos = function() {
376 return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
377 }
378
379 this.get_g = function() {
380 return self.ellipse.parent('g');
381 }
382
383 this.enter_node = function(evt) {
384 self.ellipse.attr( 'fill', '#ffccff' );
385 }
386
387 this.leave_node = function(evt) {
388 self.ellipse.attr( 'fill', '#fff' );
389 }
390
391 this.greyout_edges = function() {
392 $.each( self.node_elements, function(index, value) {
393 value.grey_out('.edge');
394 });
395 }
396
397 this.ungreyout_edges = function() {
398 $.each( self.node_elements, function(index, value) {
399 value.un_grey_out('.edge');
400 });
401 }
402
6c8d1880 403 this.reposition = function( dx, dy ) {
404 $.each( self.node_elements, function(index, value) {
405 value.reposition( dx, dy );
406 } );
407 }
408
b28e606e 409 this.move_elements = function() {
410 $.each( self.node_elements, function(index, value) {
6c8d1880 411 value.move( self.dx, self.dy );
22a70299 412 } );
b28e606e 413 }
414
415 this.reset_elements = function() {
416 $.each( self.node_elements, function(index, value) {
6c8d1880 417 value.reset();
22a70299 418 } );
b28e606e 419 }
420
421 this.update_elements = function() {
422 self.node_elements = node_elements_for(self.ellipse);
423 }
424
a84ca4de 425 this.get_witnesses = function() {
426 return readingdata[self.get_id()].witnesses
427 }
6c8d1880 428
e538eccb 429 self.set_selectable( true );
b28e606e 430}
431
432function svgshape( shape_element ) {
433 this.shape = shape_element;
6c8d1880 434 this.reposx = 0;
435 this.reposy = 0;
436 this.repositioned = this.shape.parent().data( 'repositioned' );
437 if( this.repositioned != null ) {
438 this.reposx = this.repositioned[0];
439 this.reposy = this.repositioned[1];
440 }
441 this.reposition = function (dx, dy) {
442 this.move( dx, dy );
443 this.reposx = this.reposx + dx;
444 this.reposy = this.reposy + dy;
445 this.shape.parent().data( 'repositioned', [this.reposx,this.reposy] );
446 }
b28e606e 447 this.move = function(dx,dy) {
6c8d1880 448 this.shape.attr( "transform", "translate( " + (this.reposx + dx) + " " + (this.reposy + dy) + " )" );
b28e606e 449 }
450 this.reset = function() {
6c8d1880 451 this.shape.attr( "transform", "translate( " + this.reposx + " " + this.reposy + " )" );
b28e606e 452 }
453 this.grey_out = function(filter) {
454 if( this.shape.parent(filter).size() != 0 ) {
455 this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
456 }
457 }
458 this.un_grey_out = function(filter) {
459 if( this.shape.parent(filter).size() != 0 ) {
460 this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
461 }
462 }
463}
464
465function svgpath( path_element, svg_element ) {
466 this.svg_element = svg_element;
467 this.path = path_element;
468 this.x = this.path.x;
469 this.y = this.path.y;
6c8d1880 470
471 this.reposition = function (dx, dy) {
472 this.x = this.x + dx;
473 this.y = this.y + dy;
474 this.path.x = this.x;
475 this.path.y = this.y;
476 }
477
b28e606e 478 this.move = function(dx,dy) {
479 this.path.x = this.x + dx;
480 this.path.y = this.y + dy;
481 }
6c8d1880 482
b28e606e 483 this.reset = function() {
484 this.path.x = this.x;
485 this.path.y = this.y;
486 }
6c8d1880 487
b28e606e 488 this.grey_out = function(filter) {
489 if( this.svg_element.parent(filter).size() != 0 ) {
490 this.svg_element.attr('stroke', '#e5e5e5');
491 this.svg_element.siblings('text').attr('fill', '#e5e5e5');
05485bfd 492 this.svg_element.siblings('text').attr('class', 'noselect');
b28e606e 493 }
494 }
495 this.un_grey_out = function(filter) {
496 if( this.svg_element.parent(filter).size() != 0 ) {
497 this.svg_element.attr('stroke', '#000000');
498 this.svg_element.siblings('text').attr('fill', '#000000');
05485bfd 499 this.svg_element.siblings('text').attr('class', '');
b28e606e 500 }
501 }
502}
503
504function node_elements_for( ellipse ) {
505 node_elements = get_edge_elements_for( ellipse );
506 node_elements.push( new svgshape( ellipse.siblings('text') ) );
507 node_elements.push( new svgshape( ellipse ) );
508 return node_elements;
509}
510
511function get_edge_elements_for( ellipse ) {
512 edge_elements = new Array();
45ee3b96 513 node_id = ellipse.parent().attr('id');
b28e606e 514 edge_in_pattern = new RegExp( node_id + '$' );
22a70299 515 edge_out_pattern = new RegExp( '^' + node_id + '-' );
b28e606e 516 $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
517 title = $(this).text();
518 if( edge_in_pattern.test(title) ) {
519 polygon = $(this).siblings('polygon');
520 if( polygon.size() > 0 ) {
521 edge_elements.push( new svgshape( polygon ) );
522 }
523 path_segments = $(this).siblings('path')[0].pathSegList;
524 edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
525 }
526 if( edge_out_pattern.test(title) ) {
527 path_segments = $(this).siblings('path')[0].pathSegList;
528 edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
529 }
530 });
531 return edge_elements;
532}
533
534function relation_factory() {
535 var self = this;
536 this.color_memo = null;
537 //TODO: colors hard coded for now
538 this.temp_color = '#FFA14F';
539 this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
540
541 this.create_temporary = function( source_node_id, target_node_id ) {
45ee3b96 542 var relation_id = get_relation_id( source_node_id, target_node_id );
543 var relation = $( jq( relation_id ) );
9529f69c 544 if( relation.size() == 0 ) {
b28e606e 545 draw_relation( source_node_id, target_node_id, self.temp_color );
546 } else {
547 self.color_memo = relation.children('path').attr( 'stroke' );
548 relation.children('path').attr( 'stroke', self.temp_color );
549 }
550 }
551 this.remove_temporary = function() {
552 var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
553 if( self.color_memo != null ) {
554 path_element.attr( 'stroke', self.color_memo );
555 self.color_memo = null;
556 } else {
9529f69c 557 var temporary = path_element.parent('g').remove();
558 temporary.empty();
559 temporary = null;
b28e606e 560 }
561 }
562 this.create = function( source_node_id, target_node_id, color_index ) {
563 //TODO: Protect from (color_)index out of bound..
564 var relation_color = self.relation_colors[ color_index ];
9529f69c 565 var relation = draw_relation( source_node_id, target_node_id, relation_color );
566 get_node_obj( source_node_id ).update_elements();
567 get_node_obj( target_node_id ).update_elements();
568 return relation;
b28e606e 569 }
9529f69c 570 this.toggle_active = function( relation_id ) {
45ee3b96 571 var relation = $( jq( relation_id ) );
9529f69c 572 var relation_path = relation.children('path');
573 if( !relation.data( 'active' ) ) {
574 relation_path.css( {'cursor':'pointer'} );
575 relation_path.mouseenter( function(event) {
576 outerTimer = setTimeout( function() {
577 timer = setTimeout( function() {
45ee3b96 578 var related_nodes = get_related_nodes( relation_id );
579 var source_node_id = related_nodes[0];
580 var target_node_id = related_nodes[1];
9529f69c 581 $('#delete_source_node_id').val( source_node_id );
582 $('#delete_target_node_id').val( target_node_id );
583 self.showinfo(relation);
584 }, 500 )
585 }, 1000 );
586 });
587 relation_path.mouseleave( function(event) {
588 clearTimeout(outerTimer);
589 if( timer != null ) { clearTimeout(timer); }
590 });
591 relation.data( 'active', true );
592 } else {
593 relation_path.unbind( 'mouseenter' );
594 relation_path.unbind( 'mouseleave' );
595 relation_path.css( {'cursor':'inherit'} );
596 relation.data( 'active', false );
597 }
598 }
599 this.showinfo = function(relation) {
088a14af 600 $('#delete_relation_type').text( relation.data('type') );
601 $('#delete_relation_scope').text( relation.data('scope') );
51ca18ee 602 $('#delete_relation_attributes').empty();
e4bdf660 603 var significance = ' is not ';
604 if( relation.data( 'is_significant' ) === 'yes') {
605 significance = ' is ';
606 } else if ( relation.data( 'is_significant' ) === 'maybe' ) {
607 significance = ' might be ';
608 }
609 $('#delete_relation_attributes').append(
610 "This relationship" + significance + "stemmatically significant<br/>");
51ca18ee 611 if( relation.data( 'a_derivable_from_b' ) ) {
612 $('#delete_relation_attributes').append(
613 "'" + relation.data('source_text') + "' derivable from '" + relation.data('target_text') + "'<br/>");
614 }
615 if( relation.data( 'b_derivable_from_a' ) ) {
616 $('#delete_relation_attributes').append(
617 "'" + relation.data('target_text') + "' derivable from '" + relation.data('source_text') + "'<br/>");
618 }
619 if( relation.data( 'non_independent' ) ) {
620 $('#delete_relation_attributes').append(
621 "Variance unlikely to arise coincidentally<br/>");
622 }
69a19c91 623 if( relation.data( 'note' ) ) {
088a14af 624 $('#delete_relation_note').text('note: ' + relation.data( 'note' ) );
69a19c91 625 }
9529f69c 626 var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
627 var xs = parseFloat( points[0].split(',')[0] );
628 var xe = parseFloat( points[1].split(',')[0] );
629 var ys = parseFloat( points[0].split(',')[1] );
630 var ye = parseFloat( points[3].split(',')[1] );
631 var p = svg_root.createSVGPoint();
632 p.x = xs + ((xe-xs)*1.1);
633 p.y = ye - ((ye-ys)/2);
76f05423 634 var ctm = svg_root_element.getScreenCTM();
9529f69c 635 var nx = p.matrixTransform(ctm).x;
636 var ny = p.matrixTransform(ctm).y;
637 var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
638 $('#delete-form').dialog( 'open' );
639 dialog_aria.offset({ left: nx, top: ny });
640 }
641 this.remove = function( relation_id ) {
30d0ba1e 642 if( !editable ) {
643 return;
644 }
45ee3b96 645 var relation = $( jq( relation_id ) );
9529f69c 646 relation.remove();
b28e606e 647 }
648}
649
45ee3b96 650// Utility function to create/return the ID of a relation link between
651// a source and target.
652function get_relation_id( source_id, target_id ) {
653 var idlist = [ source_id, target_id ];
654 idlist.sort();
655 return 'relation-' + idlist[0] + '-...-' + idlist[1];
656}
657
658function get_related_nodes( relation_id ) {
659 var srctotarg = relation_id.substr( 9 );
660 return srctotarg.split('-...-');
661}
662
b28e606e 663function draw_relation( source_id, target_id, relation_color ) {
9529f69c 664 var source_ellipse = get_ellipse( source_id );
665 var target_ellipse = get_ellipse( target_id );
45ee3b96 666 var relation_id = get_relation_id( source_id, target_id );
9529f69c 667 var svg = $('#svgenlargement').children('svg').svg().svg('get');
668 var path = svg.createPath();
669 var sx = parseInt( source_ellipse.attr('cx') );
670 var rx = parseInt( source_ellipse.attr('rx') );
671 var sy = parseInt( source_ellipse.attr('cy') );
672 var ex = parseInt( target_ellipse.attr('cx') );
673 var ey = parseInt( target_ellipse.attr('cy') );
9231663d 674 var relation = svg.group( $("#svgenlargement svg g"), { 'class':'relation', 'id':relation_id } );
9529f69c 675 svg.title( relation, source_id + '->' + target_id );
676 svg.path( relation, path.move( sx, sy ).curveC( sx + (2*rx), sy, ex + (2*rx), ey, ex, ey ), {fill: 'none', stroke: relation_color, strokeWidth: 4});
b28e606e 677 var relation_element = $('#svgenlargement .relation').filter( ':last' );
678 relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
9529f69c 679 return relation_element;
b28e606e 680}
681
5fe117bc 682function detach_node( readings ) {
217f5e64 683 // separate out the deleted relationships, discard for now
b6f3476b 684 if( 'DELETED' in readings ) {
685 // Remove each of the deleted relationship links.
686 $.each( readings['DELETED'], function( idx, pair ) {
687 var relation_id = get_relation_id( pair[0], pair[1] );
688 var relation = $( jq( relation_id ) );
689 if( relation.size() == 0 ) {
690 relation_id = get_relation_id( pair[1], pair[0] );
691 }
692 relation_manager.remove( relation_id );
693 });
694 delete readings['DELETED'];
695 }
a471cb0f 696 // add new node(s)
697 $.extend( readingdata, readings );
698 // remove from existing readings the witnesses for the new nodes/readings
699 $.each( readings, function( node_id, reading ) {
700 $.each( reading.witnesses, function( index, witness ) {
701 var witnesses = readingdata[ reading.orig_rdg ].witnesses;
702 readingdata[ reading.orig_rdg ].witnesses = $.removeFromArray( witness, witnesses );
703 } );
704 } );
705
a471cb0f 706 detached_edges = [];
8cd2e785 707
708 // here we detach witnesses from the existing edges accoring to what's being relayed by readings
a471cb0f 709 $.each( readings, function( node_id, reading ) {
710 var edges = edges_of( get_ellipse( reading.orig_rdg ) );
711 incoming_remaining = [];
712 outgoing_remaining = [];
713 $.each( reading.witnesses, function( index, witness ) {
714 incoming_remaining.push( witness );
715 outgoing_remaining.push( witness );
716 } );
717 $.each( edges, function( index, edge ) {
718 detached_edge = edge.detach_witnesses( reading.witnesses );
719 if( detached_edge != null ) {
720 detached_edges.push( detached_edge );
721 $.each( detached_edge.witnesses, function( index, witness ) {
722 if( detached_edge.is_incoming == true ) {
723 incoming_remaining = $.removeFromArray( witness, incoming_remaining );
724 } else {
725 outgoing_remaining = $.removeFromArray( witness, outgoing_remaining );
726 }
727 } );
728 }
729 } );
8cd2e785 730
60c66cd2 731 // After detaching we still need to check if for *all* readings
8cd2e785 732 // an edge was detached. It may be that a witness was not
733 // explicitly named on an edge but was part of a 'majority' edge
734 // in which case we need to duplicate and name that edge after those
735 // remaining witnesses.
a471cb0f 736 if( outgoing_remaining.length > 0 ) {
a471cb0f 737 $.each( edges, function( index, edge ) {
a471cb0f 738 if( edge.get_label() == 'majority' && !edge.is_incoming ) {
739 detached_edges.push( edge.clone_for( outgoing_remaining ) );
740 }
741 } );
742 }
743 if( incoming_remaining.length > 0 ) {
a471cb0f 744 $.each( edges, function( index, edge ) {
745 if( edge.get_label() == 'majority' && edge.is_incoming ) {
dc8a13bd 746 detached_edges.push( edge.clone_for( incoming_remaining ) );
a471cb0f 747 }
748 } );
749 }
60c66cd2 750
22a70299 751 // Finally multiple selected nodes may share edges
752 var copy_array = [];
753 $.each( detached_edges, function( index, edge ) {
754 var do_copy = true;
755 $.each( copy_array, function( index, copy_edge ) {
756 if( copy_edge.g_elem.attr( 'id' ) == edge.g_elem.attr( 'id' ) ) { do_copy = false }
757 } );
758 if( do_copy == true ) {
759 copy_array.push( edge );
760 }
761 } );
762 detached_edges = copy_array;
763
60c66cd2 764 // Lots of unabstracted knowledge down here :/
765 // Clone original node/reading, rename/id it..
766 duplicate_node = get_ellipse( reading.orig_rdg ).parent().clone();
767 duplicate_node.attr( 'id', node_id );
768 duplicate_node.children( 'title' ).text( node_id );
6c8d1880 769
770 // This needs somehow to move to node or even to shapes! #repositioned
771 duplicate_node_data = get_ellipse( reading.orig_rdg ).parent().data( 'repositioned' );
22a70299 772 if( duplicate_node_data != null ) {
6c8d1880 773 duplicate_node.children( 'ellipse' ).parent().data( 'repositioned', duplicate_node_data );
22a70299 774 }
60c66cd2 775
776 // Add the node and all new edges into the graph
931ed236 777 var graph_root = $('#svgenlargement svg g.graph');
60c66cd2 778 graph_root.append( duplicate_node );
779 $.each( detached_edges, function( index, edge ) {
dc8a13bd 780 id_suffix = node_id.slice( node_id.indexOf( '_' ) );
781 edge.g_elem.attr( 'id', ( edge.g_elem.attr( 'id' ) + id_suffix ) );
60c66cd2 782 edge_title = edge.g_elem.children( 'title' ).text();
22a70299 783 edge_weight = 0.8 + ( 0.2 * edge.witnesses.length );
60c66cd2 784 edge_title = edge_title.replace( reading.orig_rdg, node_id );
785 edge.g_elem.children( 'title' ).text( edge_title );
22a70299 786 edge.g_elem.children( 'path').attr( 'stroke-width', edge_weight );
60c66cd2 787 // Reg unabstracted knowledge: isn't it more elegant to make
788 // it edge.append_to( graph_root )?
789 graph_root.append( edge.g_elem );
790 } );
22a70299 791
792 // Make the detached node a real node_obj
793 var ellipse_elem = get_ellipse( node_id );
794 var new_node = new node_obj( ellipse_elem );
795 ellipse_elem.data( 'node_obj', new_node );
796
60c66cd2 797 // Move the node somewhat up for 'dramatic effect' :-p
9231663d 798 new_node.reposition( 0, -70 );
60c66cd2 799
a471cb0f 800 } );
60c66cd2 801
9231663d 802}
a471cb0f 803
9231663d 804function merge_nodes( source_node_id, target_node_id, consequences ) {
805 if( consequences.status != null && consequences.status == 'ok' ) {
806 merge_node( source_node_id, target_node_id );
807 if( consequences.checkalign != null ) {
808 $.each( consequences.checkalign, function( index, node_ids ) {
0c4354f6 809 var temp_relation = draw_relation( node_ids[0], node_ids[1], "#89a02c" );
9231663d 810 var sy = parseInt( temp_relation.children('path').attr('d').split('C')[0].split(',')[1] );
811 var ey = parseInt( temp_relation.children('path').attr('d').split(' ')[2].split(',')[1] );
812 var yC = ey + (( sy - ey )/2);
813 // TODO: compute xC to be always the same distance to the amplitude of the curve
814 var xC = parseInt( temp_relation.children('path').attr('d').split(' ')[1].split(',')[0] );
815 var svg = $('#svgenlargement').children('svg').svg('get');
816 parent_g = svg.group( $('#svgenlargement svg g') );
817 var ids_text = node_ids[0] + '-' + node_ids[1];
818 var merge_id = 'merge-' + ids_text;
48156ccd 819 svg.image( parent_g, xC, (yC-8), 16, 16, merge_button_yes, { id: merge_id } );
820 svg.image( parent_g, (xC+20), (yC-8), 16, 16, merge_button_no, { id: 'no' + merge_id } );
9231663d 821 $( '#' + merge_id ).hover( function(){ $(this).addClass( 'draggable' ) }, function(){ $(this).removeClass( 'draggable' ) } );
822 $( '#no' + merge_id ).hover( function(){ $(this).addClass( 'draggable' ) }, function(){ $(this).removeClass( 'draggable' ) } );
823 $( '#' + merge_id ).click( function( evt ){
824 merge_node( node_ids[0], node_ids[1] );
825 temp_relation.remove();
826 $( '#' + merge_id ).parent().remove();
759f1868 827 //notify backend
828 var ncpath = getTextURL( 'merge' );
aaf27b2e 829 var form_values = "source_id=" + node_ids[0] + "&target_id=" + node_ids[1] + "&single=true";
759f1868 830 $.post( ncpath, form_values );
9231663d 831 } );
832 $( '#no' + merge_id ).click( function( evt ) {
833 temp_relation.remove();
834 $( '#' + merge_id ).parent().remove();
835 } );
836 } );
837 }
838 }
839}
840
841function merge_node( source_node_id, target_node_id ) {
842 $.each( edges_of( get_ellipse( source_node_id ) ), function( index, edge ) {
843 if( edge.is_incoming == true ) {
844 edge.attach_endpoint( target_node_id );
845 } else {
846 edge.attach_startpoint( target_node_id );
847 }
848 } );
849 $( jq( source_node_id ) ).remove();
a471cb0f 850}
851
c1add777 852function Marquee() {
853
854 var self = this;
855
f6516f22 856 this.x = 0;
857 this.y = 0;
858 this.dx = 0;
859 this.dy = 0;
c1add777 860 this.enlargementOffset = $('#svgenlargement').offset();
861 this.svg_rect = $('#svgenlargement svg').svg('get');
862
863 this.show = function( event ) {
f6516f22 864 self.x = event.clientX;
865 self.y = event.clientY;
c1add777 866 p = svg_root.createSVGPoint();
867 p.x = event.clientX - self.enlargementOffset.left;
868 p.y = event.clientY - self.enlargementOffset.top;
c1add777 869 self.svg_rect.rect( p.x, p.y, 0, 0, { fill: 'black', 'fill-opacity': '0.1', stroke: 'black', 'stroke-dasharray': '4,2', strokeWidth: '0.02em', id: 'marquee' } );
870 };
871
872 this.expand = function( event ) {
f6516f22 873 self.dx = (event.clientX - self.x);
874 self.dy = (event.clientY - self.y);
c1add777 875 var rect = $('#marquee');
f6516f22 876 if( rect.length != 0 ) {
877 var rect_w = Math.abs( self.dx );
878 var rect_h = Math.abs( self.dy );
879 var rect_x = self.x - self.enlargementOffset.left;
880 var rect_y = self.y - self.enlargementOffset.top;
881 if( self.dx < 0 ) { rect_x = rect_x - rect_w }
882 if( self.dy < 0 ) { rect_y = rect_y - rect_h }
883 rect.attr("x", rect_x).attr("y", rect_y).attr("width", rect_w).attr("height", rect_h);
c1add777 884 }
885 };
886
a84ca4de 887 this.select = function() {
c1add777 888 var rect = $('#marquee');
889 if( rect.length != 0 ) {
e538eccb 890 //unselect any possible selected first
22a70299 891 //TODO: unless SHIFT?
e538eccb 892 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
893 $('ellipse[fill="#9999ff"]').each( function() {
894 $(this).data( 'node_obj' ).set_draggable( false );
895 } );
896 }
897 //compute dimension of marquee
c1add777 898 var left = $('#marquee').offset().left;
899 var top = $('#marquee').offset().top;
900 var right = left + parseInt( $('#marquee').attr( 'width' ) );
901 var bottom = top + parseInt( $('#marquee').attr( 'height' ) );
902 var tf = svg_root_element.getScreenCTM().inverse();
903 var p = svg_root.createSVGPoint();
904 p.x=left;
905 p.y=top;
906 var cx_min = p.matrixTransform(tf).x;
907 var cy_min = p.matrixTransform(tf).y;
908 p.x=right;
909 p.y=bottom;
910 var cx_max = p.matrixTransform(tf).x;
911 var cy_max = p.matrixTransform(tf).y;
e538eccb 912 //select any node with its center inside the marquee
5fe117bc 913 var readings = [];
e538eccb 914 //also merge witness sets from nodes
a84ca4de 915 var witnesses = [];
c1add777 916 $('#svgenlargement ellipse').each( function( index ) {
917 var cx = parseInt( $(this).attr('cx') );
918 var cy = parseInt( $(this).attr('cy') );
6c8d1880 919
920 // This needs somehow to move to node or even to shapes! #repositioned
921 // We should ask something more aling the lines of: nodes.each { |item| node.selected? }
922 var org_translate = $(this).parent().data( 'repositioned' );
22a70299 923 if( org_translate != null ) {
924 cx = cx + org_translate[0];
925 cy = cy + org_translate[1];
926 }
6c8d1880 927
c1add777 928 if( cx > cx_min && cx < cx_max) {
929 if( cy > cy_min && cy < cy_max) {
930 // we actually heve no real 'selected' state for nodes, except coloring
e538eccb 931 $(this).attr( 'fill', '#9999ff' );
5fe117bc 932 // Take note of the selected reading(s) and applicable witness(es)
933 // so we can populate the multipleselect-form
934 readings.push( $(this).parent().attr('id') );
a84ca4de 935 var this_witnesses = $(this).data( 'node_obj' ).get_witnesses();
936 witnesses = arrayUnique( witnesses.concat( this_witnesses ) );
c1add777 937 }
938 }
939 });
e538eccb 940 if( $('ellipse[fill="#9999ff"]').size() > 0 ) {
5fe117bc 941 //add intersection of witnesses sets to the multi select form and open it
942 $('#detach_collated_form').empty();
943 $.each( readings, function( index, value ) {
944 $('#detach_collated_form').append( $('<input>').attr(
945 "type", "hidden").attr("name", "readings[]").attr(
946 "value", value ) );
947 });
948 $.each( witnesses, function( index, value ) {
949 $('#detach_collated_form').append(
950 '<input type="checkbox" name="witnesses[]" value="' + value
951 + '">' + value + '<br>' );
a84ca4de 952 });
5fe117bc 953 $('#multiple_selected_readings').attr('value', readings.join(',') );
a84ca4de 954 $('#multipleselect-form').dialog( 'open' );
955 }
c1add777 956 self.svg_rect.remove( $('#marquee') );
957 }
958 };
959
f6516f22 960 this.unselect = function() {
e538eccb 961 $('ellipse[fill="#9999ff"]').attr( 'fill', '#fff' );
f6516f22 962 }
963
c1add777 964}
965
b001c73d 966function readings_equivalent( source, target ) {
967 var sourcetext = readingdata[source].text;
968 var targettext = readingdata[target].text;
969 if( sourcetext === targettext ) {
970 return true;
971 }
972 // Lowercase and strip punctuation from both and compare again
f069bb5c 973 var nonwc = XRegExp('[^\\p{L}\\s]|_');
974 var stlc = XRegExp.replace( sourcetext.toLocaleLowerCase(), nonwc, "", 'all' );
975 var ttlc = XRegExp.replace( targettext.toLocaleLowerCase(), nonwc, "", 'all' );
b001c73d 976 if( stlc === ttlc ) {
977 return true;
978 }
979 return false;
980}
981
9529f69c 982
b28e606e 983$(document).ready(function () {
9529f69c 984
985 timer = null;
b28e606e 986 relation_manager = new relation_factory();
987
c1add777 988 $('#update_workspace_button').data('locked', false);
b001c73d 989
990 // Set up the mouse events on the SVG enlargement
9529f69c 991 $('#enlargement').mousedown(function (event) {
b28e606e 992 $(this)
9529f69c 993 .data('down', true)
994 .data('x', event.clientX)
995 .data('y', event.clientY)
996 .data('scrollLeft', this.scrollLeft)
c1add777 997 stateTf = svg_root_element.getCTM().inverse();
998 var p = svg_root.createSVGPoint();
999 p.x = event.clientX;
1000 p.y = event.clientY;
1001 stateOrigin = p.matrixTransform(stateTf);
1002
1003 // Activate marquee if in interaction mode
1004 if( $('#update_workspace_button').data('locked') == true ) { marquee.show( event ) };
1005
1006 event.returnValue = false;
1007 event.preventDefault();
1008 return false;
b28e606e 1009 }).mouseup(function (event) {
a84ca4de 1010 marquee.select();
c1add777 1011 $(this).data('down', false);
b28e606e 1012 }).mousemove(function (event) {
9529f69c 1013 if( timer != null ) { clearTimeout(timer); }
1014 if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
1015 var p = svg_root.createSVGPoint();
1016 p.x = event.clientX;
1017 p.y = event.clientY;
1018 p = p.matrixTransform(stateTf);
1019 var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
1020 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
76f05423 1021 svg_root_element.setAttribute("transform", s);
b28e606e 1022 }
c1add777 1023 marquee.expand( event );
76f05423 1024 event.returnValue = false;
1025 event.preventDefault();
b28e606e 1026 }).mousewheel(function (event, delta) {
9529f69c 1027 event.returnValue = false;
1028 event.preventDefault();
1029 if ( $('#update_workspace_button').data('locked') == false ) {
76f05423 1030 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
1031 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
9529f69c 1032 if( delta < -9 ) { delta = -9 };
1033 var z = 1 + delta/10;
76f05423 1034 z = delta > 0 ? 1 : -1;
1035 var g = svg_root_element;
1036 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
9529f69c 1037 var root = svg_root;
1038 var p = root.createSVGPoint();
76f05423 1039 p.x = event.originalEvent.clientX;
1040 p.y = event.originalEvent.clientY;
9529f69c 1041 p = p.matrixTransform(g.getCTM().inverse());
76f05423 1042 var scaleLevel = 1+(z/20);
1043 var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
9529f69c 1044 var matrix = g.getCTM().multiply(k);
1045 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
1046 g.setAttribute("transform", s);
1047 }
1048 }
b28e606e 1049 }).css({
1050 'overflow' : 'hidden',
1051 'cursor' : '-moz-grab'
1052 });
1053
c1add777 1054
b001c73d 1055 // Set up the relationship creation dialog. This also functions as the reading
1056 // merge dialog where appropriate.
b001c73d 1057
30d0ba1e 1058 if( editable ) {
9231663d 1059 $( '#dialog-form' ).dialog( {
30d0ba1e 1060 autoOpen: false,
e4bdf660 1061 height: 350,
51ca18ee 1062 width: 330,
30d0ba1e 1063 modal: true,
1064 buttons: {
9231663d 1065 'Merge readings': function( evt ) {
1066 $( evt.target ).button( 'disable' );
1067 $( '#status' ).empty();
1068 form_values = $( '#collapse_node_form' ).serialize();
b001c73d 1069 ncpath = getTextURL( 'merge' );
9231663d 1070 var jqjson = $.post( ncpath, form_values, function( data ) {
1071 merge_nodes( $( '#source_node_id' ).val(), $( '#target_node_id' ).val(), data );
bfb6d17f 1072 $(evt.target).button( 'enable' );
9231663d 1073 $( '#dialog-form' ).dialog( 'close' );
1074 } );
b001c73d 1075 },
1076 OK: function( evt ) {
9231663d 1077 $( evt.target ).button( 'disable' );
1078 $( '#status' ).empty();
1079 form_values = $( '#collapse_node_form' ).serialize();
30d0ba1e 1080 ncpath = getTextURL( 'relationships' );
9231663d 1081 var jqjson = $.post( ncpath, form_values, function( data ) {
1082 $.each( data, function( item, source_target ) {
30d0ba1e 1083 var source_found = get_ellipse( source_target[0] );
1084 var target_found = get_ellipse( source_target[1] );
9231663d 1085 var relation_found = $.inArray( source_target[2], $( '#keymap' ).data( 'relations' ) );
30d0ba1e 1086 if( source_found.size() && target_found.size() && relation_found > -1 ) {
1087 var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
45ee3b96 1088 relation_manager.toggle_active( relation.attr('id') );
51ca18ee 1089 $.each( $('#collapse_node_form').serializeArray(), function( i, k ) {
1090 relation.data( k.name, k.value );
1091 });
7b54e481 1092 }
9231663d 1093 $(evt.target).button( 'enable' );
30d0ba1e 1094 });
9231663d 1095 $( '#dialog-form' ).dialog( 'close' );
30d0ba1e 1096 }, 'json' );
1097 },
1098 Cancel: function() {
9231663d 1099 $( this ).dialog( 'close' );
30d0ba1e 1100 }
1101 },
1102 create: function(event, ui) {
1103 $(this).data( 'relation_drawn', false );
a166dca8 1104 $('#rel_type').data( 'changed_after_open', false );
56e3972e 1105 $.each( relationship_types, function(index, typedef) {
1106 $('#rel_type').append( $('<option />').attr( "value", typedef.name ).text(typedef.name) );
1107 });
1108 $.each( relationship_scopes, function(index, value) {
1109 $('#scope').append( $('<option />').attr( "value", value ).text(value) );
a166dca8 1110 });
e4bdf660 1111 $.each( ternary_values, function( index, value ) {
1112 $('#is_significant').append( $('<option />').attr( "value", value ).text(value) );
1113 });
1114 // Handler to reset fields to default, the first time the relationship
1115 // is changed after opening the form.
a166dca8 1116 $('#rel_type').change( function () {
1117 if( !$(this).data( 'changed_after_open' ) ) {
1118 $('#note').val('');
e4bdf660 1119 $(this).find(':checked').removeAttr('checked');
a166dca8 1120 }
1121 $(this).data( 'changed_after_open', true );
1122 });
30d0ba1e 1123 },
1124 open: function() {
b001c73d 1125 relation_manager.create_temporary(
1126 $('#source_node_id').val(), $('#target_node_id').val() );
1127 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1128 if( readings_equivalent( $('#source_node_id').val(),
1129 $('#target_node_id').val() ) ) {
1130 buttonset.find( "button:contains('Merge readings')" ).show();
1131 } else {
1132 buttonset.find( "button:contains('Merge readings')" ).hide();
1133 }
30d0ba1e 1134 $(".ui-widget-overlay").css("background", "none");
1135 $("#dialog_overlay").show();
1136 $("#dialog_overlay").height( $("#enlargement_container").height() );
1137 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1138 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a166dca8 1139 $('#rel_type').data( 'changed_after_open', false );
30d0ba1e 1140 },
1141 close: function() {
1142 relation_manager.remove_temporary();
1143 $( '#status' ).empty();
1144 $("#dialog_overlay").hide();
1145 }
1146 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
e4bdf660 1147 if( ( ajaxSettings.url == getTextURL('relationships')
1148 || ajaxSettings.url == getTextURL('merge') )
21e6ebc7 1149 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1150 var error;
1151 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1152 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1153 } else {
1154 try {
1155 var errobj = jQuery.parseJSON( jqXHR.responseText );
1156 error = errobj.error + '</br>The relationship cannot be made.</p>';
1157 } catch(e) {
1158 error = jqXHR.responseText;
1159 }
1160 }
1161 $('#status').append( '<p class="error">Error: ' + error );
1162 }
1163 $(event.target).parent().find('.ui-button').button("enable");
30d0ba1e 1164 } );
1165 }
b28e606e 1166
b001c73d 1167 // Set up the relationship info display and deletion dialog.
9529f69c 1168 $( "#delete-form" ).dialog({
1169 autoOpen: false,
69a19c91 1170 height: 135,
d5b3c010 1171 width: 300,
9529f69c 1172 modal: false,
b001c73d 1173 buttons: {
1174 OK: function() { $( this ).dialog( "close" ); },
1175 "Delete all": function () { delete_relation( true ); },
1176 Delete: function() { delete_relation( false ); }
1177 },
9529f69c 1178 create: function(event, ui) {
30d0ba1e 1179 // TODO What is this logic doing?
a84ca4de 1180 // This scales the buttons in the dialog and makes it look proper
1181 // Not sure how essential it is, does anything break if it's not here?
9529f69c 1182 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
b001c73d 1183 buttonset.find( "button:contains('OK')" ).css( 'float', 'right' );
a84ca4de 1184 // A: This makes sure that the pop up delete relation dialogue for a hovered over
1185 // relation auto closes if the user doesn't engage (mouseover) with it.
9529f69c 1186 var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");
1187 dialog_aria.mouseenter( function() {
1188 if( mouseWait != null ) { clearTimeout(mouseWait) };
1189 })
1190 dialog_aria.mouseleave( function() {
1191 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1192 })
1193 },
1194 open: function() {
b001c73d 1195 // Show the appropriate buttons...
1196 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' )
1197 // If the user can't edit, show only the OK button
088a14af 1198 if( !editable ) {
b001c73d 1199 buttonset.find( "button:contains('Delete')" ).hide();
1200 // If the relationship scope is local, show only OK and Delete
088a14af 1201 } else if( $('#delete_relation_scope').text() === 'local' ) {
1202 $( this ).dialog( "option", "width", 160 );
b001c73d 1203 buttonset.find( "button:contains('Delete')" ).show();
1204 buttonset.find( "button:contains('Delete all')" ).hide();
1205 // Otherwise, show all three
088a14af 1206 } else {
1207 $( this ).dialog( "option", "width", 200 );
b001c73d 1208 buttonset.find( "button:contains('Delete')" ).show();
088a14af 1209 }
9529f69c 1210 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
1211 },
088a14af 1212 close: function() {}
9529f69c 1213 });
1214
a84ca4de 1215 $( "#multipleselect-form" ).dialog({
1216 autoOpen: false,
1217 height: 150,
1218 width: 250,
1219 modal: true,
5fe117bc 1220 buttons: {
22a70299 1221 Cancel: function() { $( this ).dialog( "close" ); },
1222 Detach: function ( evt ) {
1223 var self = $(this);
1224 $( evt.target ).button( "disable" );
1225 var form_values = $('#detach_collated_form').serialize();
1226 ncpath = getTextURL( 'duplicate' );
1227 var jqjson = $.post( ncpath, form_values, function(data) {
1228 detach_node( data );
1229 $(evt.target).button("enable");
1230 self.dialog( "close" );
1231 } );
1232 }
7ef4a584 1233 },
1234 create: function(event, ui) {
a84ca4de 1235 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
1236 buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
1237 },
1238 open: function() {
1239 $( this ).dialog( "option", "width", 200 );
e538eccb 1240 $(".ui-widget-overlay").css("background", "none");
5fe117bc 1241 $('#multipleselect-form-status').empty();
e538eccb 1242 $("#dialog_overlay").show();
1243 $("#dialog_overlay").height( $("#enlargement_container").height() );
1244 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1245 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a84ca4de 1246 },
e538eccb 1247 close: function() {
1248 marquee.unselect();
1249 $("#dialog_overlay").hide();
1250 }
5fe117bc 1251 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
1252 if( ajaxSettings.url == getTextURL('duplicate')
1253 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
1254 var error;
1255 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1256 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1257 } else {
1258 try {
1259 var errobj = jQuery.parseJSON( jqXHR.responseText );
1260 error = errobj.error + '</br>The relationship cannot be made.</p>';
1261 } catch(e) {
1262 error = jqXHR.responseText;
1263 }
1264 }
1265 $('#multipleselect-form-status').append( '<p class="error">Error: ' + error );
1266 }
1267 $(event.target).parent().find('.ui-button').button("enable");
1268 });
1269
a84ca4de 1270
088a14af 1271 // Helpers for relationship deletion
1272
1273 function delete_relation( scopewide ) {
1274 form_values = $('#delete_relation_form').serialize();
1275 if( scopewide ) {
1276 form_values += "&scopewide=true";
1277 }
1278 ncpath = getTextURL( 'relationships' );
1279 var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
1280 $.each( data, function(item, source_target) {
1281 relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
1282 });
1283 $( "#delete-form" ).dialog( "close" );
1284 }, dataType: 'json', type: 'DELETE' });
1285 }
1286
1287 function toggle_relation_active( node_id ) {
1288 $('#svgenlargement .relation').find( "title:contains('" + node_id + "')" ).each( function(index) {
1289 matchid = new RegExp( "^" + node_id );
1290 if( $(this).text().match( matchid ) != null ) {
1291 var relation_id = $(this).parent().attr('id');
1292 relation_manager.toggle_active( relation_id );
1293 };
1294 });
1295 }
1296
487674b9 1297 // function for reading form dialog should go here;
1298 // just hide the element for now if we don't have morphology
1299 if( can_morphologize ) {
1300 $('#reading-form').dialog({
1301 autoOpen: false,
1302 // height: 400,
1303 width: 450,
1304 modal: true,
1305 buttons: {
1306 Cancel: function() {
1307 $( this ).dialog( "close" );
1308 },
1309 Update: function( evt ) {
1310 // Disable the button
1311 $(evt.target).button("disable");
1312 $('#reading_status').empty();
1313 var reading_id = $('#reading_id').val()
1314 form_values = {
1315 'id' : reading_id,
1316 'is_nonsense': $('#reading_is_nonsense').is(':checked'),
1317 'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
1318 'normal_form': $('#reading_normal_form').val() };
1319 // Add the morphology values
1320 $('.reading_morphology').each( function() {
1321 if( $(this).val() != '(Click to select)' ) {
1322 var rmid = $(this).attr('id');
1323 rmid = rmid.substring(8);
1324 form_values[rmid] = $(this).val();
1325 }
45ee3b96 1326 });
487674b9 1327 // Make the JSON call
1328 ncpath = getReadingURL( reading_id );
1329 var reading_element = readingdata[reading_id];
1330 // $(':button :contains("Update")').attr("disabled", true);
1331 var jqjson = $.post( ncpath, form_values, function(data) {
1332 $.each( data, function(key, value) {
1333 reading_element[key] = value;
1334 });
1335 if( $('#update_workspace_button').data('locked') == false ) {
1336 color_inactive( get_ellipse( reading_id ) );
1337 }
1338 $(evt.target).button("enable");
1339 $( "#reading-form" ).dialog( "close" );
1340 });
1341 // Re-color the node if necessary
1342 return false;
1343 }
1344 },
1345 create: function() {
30d0ba1e 1346 if( !editable ) {
1347 // Get rid of the disallowed editing UI bits
1348 $( this ).dialog( "option", "buttons",
1349 [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
1350 $('#reading_relemmatize').hide();
1351 }
487674b9 1352 },
1353 open: function() {
1354 $(".ui-widget-overlay").css("background", "none");
1355 $("#dialog_overlay").show();
1356 $('#reading_status').empty();
1357 $("#dialog_overlay").height( $("#enlargement_container").height() );
1358 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1359 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1360 $("#reading-form").parent().find('.ui-button').button("enable");
1361 },
1362 close: function() {
1363 $("#dialog_overlay").hide();
1364 }
1365 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
21e6ebc7 1366 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
487674b9 1367 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
21e6ebc7 1368 var error;
1369 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1370 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1371 } else {
1372 try {
1373 var errobj = jQuery.parseJSON( jqXHR.responseText );
1374 error = errobj.error + '</br>The relationship cannot be made.</p>';
1375 } catch(e) {
1376 error = jqXHR.responseText;
1377 }
1378 }
1379 $('#status').append( '<p class="error">Error: ' + error );
1380 }
1381 $(event.target).parent().find('.ui-button').button("enable");
487674b9 1382 });
1383 } else {
1384 $('#reading-form').hide();
45ee3b96 1385 }
4c41c02c 1386
76f05423 1387
b28e606e 1388 $('#update_workspace_button').click( function() {
30d0ba1e 1389 if( !editable ) {
1390 return;
1391 }
b28e606e 1392 var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
76f05423 1393 mouse_scale = svg_root_element.getScreenCTM().a;
9529f69c 1394 if( $(this).data('locked') == true ) {
1395 $('#svgenlargement ellipse' ).each( function( index ) {
1396 if( $(this).data( 'node_obj' ) != null ) {
1397 $(this).data( 'node_obj' ).ungreyout_edges();
e538eccb 1398 $(this).data( 'node_obj' ).set_selectable( false );
1399 color_inactive( $(this) );
9529f69c 1400 var node_id = $(this).data( 'node_obj' ).get_id();
1401 toggle_relation_active( node_id );
1402 $(this).data( 'node_obj', null );
1403 }
b28e606e 1404 })
b28e606e 1405 $(this).data('locked', false);
9529f69c 1406 $(this).css('background-position', '0px 44px');
b28e606e 1407 } else {
9529f69c 1408 var left = $('#enlargement').offset().left;
1409 var right = left + $('#enlargement').width();
76f05423 1410 var tf = svg_root_element.getScreenCTM().inverse();
9529f69c 1411 var p = svg_root.createSVGPoint();
1412 p.x=left;
1413 p.y=100;
1414 var cx_min = p.matrixTransform(tf).x;
1415 p.x=right;
1416 var cx_max = p.matrixTransform(tf).x;
1417 $('#svgenlargement ellipse').each( function( index ) {
1418 var cx = parseInt( $(this).attr('cx') );
1419 if( cx > cx_min && cx < cx_max) {
1420 if( $(this).data( 'node_obj' ) == null ) {
1421 $(this).data( 'node_obj', new node_obj( $(this) ) );
1422 } else {
e538eccb 1423 $(this).data( 'node_obj' ).set_selectable( true );
9529f69c 1424 }
1425 $(this).data( 'node_obj' ).greyout_edges();
1426 var node_id = $(this).data( 'node_obj' ).get_id();
1427 toggle_relation_active( node_id );
b28e606e 1428 }
9529f69c 1429 });
1430 $(this).css('background-position', '0px 0px');
b28e606e 1431 $(this).data('locked', true );
b28e606e 1432 }
1433 });
30d0ba1e 1434
1435 if( !editable ) {
1436 // Hide the unused elements
1437 $('#dialog-form').hide();
1438 $('#update_workspace_button').hide();
1439 }
1440
b28e606e 1441
e847b186 1442 $('.helptag').popupWindow({
1443 height:500,
1444 width:800,
1445 top:50,
1446 left:50,
1447 scrollbars:1
1448 });
1449
76f05423 1450 expandFillPageClients();
1451 $(window).resize(function() {
1452 expandFillPageClients();
1453 });
1454
9529f69c 1455});
b28e606e 1456
1457
76f05423 1458function expandFillPageClients() {
1459 $('.fillPage').each(function () {
1460 $(this).height($(window).height() - $(this).offset().top - MARGIN);
1461 });
1462}
1463
1464function loadSVG(svgData) {
1465 var svgElement = $('#svgenlargement');
1466
1467 $(svgElement).svg('destroy');
1468
1469 $(svgElement).svg({
1470 loadURL: svgData,
1471 onLoad : svgEnlargementLoaded
1472 });
1473}
1474
1475
c1add777 1476
76f05423 1477/* OS Gadget stuff
1478
1479function svg_select_callback(topic, data, subscriberData) {
1480 svgData = data;
1481 loadSVG(svgData);
1482}
1483
1484function loaded() {
1485 var prefs = new gadgets.Prefs();
1486 var preferredHeight = parseInt(prefs.getString('height'));
1487 if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
1488 expandFillPageClients();
1489}
1490
1491if (gadgets.util.hasFeature('pubsub-2')) {
1492 gadgets.HubSettings.onConnect = function(hum, suc, err) {
1493 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
1494 loaded();
1495 };
1496}
1497else gadgets.util.registerOnLoadHandler(loaded);
1498*/