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