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