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