Added witnesses selection form interactivity; issues with selection state to be resolved.
[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
a84ca4de 8function arrayUnique(array) {
9 var a = array.concat();
10 for(var i=0; i<a.length; ++i) {
11 for(var j=i+1; j<a.length; ++j) {
12 if(a[i] === a[j])
13 a.splice(j--, 1);
14 }
15 }
16 return a;
17};
18
5f15640c 19function getTextURL( which ) {
3f9d7ae5 20 return basepath + textid + '/' + which;
5f15640c 21}
22
23function getReadingURL( reading_id ) {
3f9d7ae5 24 return basepath + textid + '/reading/' + reading_id;
b28e606e 25}
26
45ee3b96 27// Make an XML ID into a valid selector
28function jq(myid) {
29 return '#' + myid.replace(/(:|\.)/g,'\\$1');
30}
31
065c7cf2 32// Actions for opening the reading panel
33function node_dblclick_listener( evt ) {
34 // Open the reading dialogue for the given node.
35 // First get the reading info
36 var reading_id = $(this).attr('id');
37 var reading_info = readingdata[reading_id];
38 // and then populate the dialog box with it.
39 // Set the easy properties first
40 $('#reading-form').dialog( 'option', 'title', 'Reading information for "' + reading_info['text'] + '"' );
41 $('#reading_id').val( reading_id );
798fa939 42 toggle_checkbox( $('#reading_is_nonsense'), reading_info['is_nonsense'] );
43 toggle_checkbox( $('#reading_grammar_invalid'), reading_info['grammar_invalid'] );
065c7cf2 44 // Use .text as a backup for .normal_form
45 var normal_form = reading_info['normal_form'];
46 if( !normal_form ) {
47 normal_form = reading_info['text'];
48 }
49 var nfboxsize = 10;
50 if( normal_form.length > 9 ) {
51 nfboxsize = normal_form.length + 1;
52 }
53 $('#reading_normal_form').attr( 'size', nfboxsize )
54 $('#reading_normal_form').val( normal_form );
5539cba3 55 if( editable ) {
56 // Fill in the witnesses for the de-collation box.
57 $('#reading_decollate_witnesses').empty();
58 $.each( reading_info['witnesses'], function( idx, wit ) {
59 $('#reading_decollate_witnesses').append( $('<option/>').attr(
60 'value', wit ).text( wit ) );
61 });
62 }
065c7cf2 63 // Now do the morphological properties.
0dcdd5ec 64 morphology_form( reading_info['lexemes'] );
065c7cf2 65 // and then open the dialog.
0dcdd5ec 66 $('#reading-form').dialog("open");
67}
68
798fa939 69function toggle_checkbox( box, value ) {
70 if( value == null ) {
71 value = false;
72 }
73 box.attr('checked', value );
74}
75
0dcdd5ec 76function morphology_form ( lexlist ) {
487674b9 77 if( lexlist.length ) {
78 $('#morph_outer').show();
79 $('#morphology').empty();
80 $.each( lexlist, function( idx, lex ) {
81 var morphoptions = [];
82 if( 'wordform_matchlist' in lex ) {
83 $.each( lex['wordform_matchlist'], function( tdx, tag ) {
84 var tagstr = stringify_wordform( tag );
85 morphoptions.push( tagstr );
86 });
87 }
88 var formtag = 'morphology_' + idx;
89 var formstr = '';
90 if( 'form' in lex ) {
91 formstr = stringify_wordform( lex['form'] );
92 }
93 var form_morph_elements = morph_elements(
94 formtag, lex['string'], formstr, morphoptions );
95 $.each( form_morph_elements, function( idx, el ) {
96 $('#morphology').append( el );
08f8443a 97 });
065c7cf2 98 });
487674b9 99 } else {
100 $('#morph_outer').hide();
101 }
065c7cf2 102}
103
104function stringify_wordform ( tag ) {
08f8443a 105 if( tag ) {
106 var elements = tag.split(' // ');
107 return elements[1] + ' // ' + elements[2];
108 }
109 return ''
065c7cf2 110}
111
d1132306 112function morph_elements ( formtag, formtxt, currform, morphoptions ) {
113 var clicktag = '(Click to select)';
114 if ( !currform ) {
115 currform = clicktag;
116 }
065c7cf2 117 var formlabel = $('<label/>').attr( 'id', 'label_' + formtag ).attr(
d1132306 118 'for', 'reading_' + formtag ).text( formtxt + ': ' );
065c7cf2 119 var forminput = $('<input/>').attr( 'id', 'reading_' + formtag ).attr(
0dcdd5ec 120 'name', 'reading_' + formtag ).attr( 'size', '50' ).attr(
121 'class', 'reading_morphology' ).val( currform );
d1132306 122 forminput.autocomplete({ source: morphoptions, minLength: 0 });
123 forminput.focus( function() {
124 if( $(this).val() == clicktag ) {
125 $(this).val('');
126 }
127 $(this).autocomplete('search', '')
128 });
065c7cf2 129 var morphel = [ formlabel, forminput, $('<br/>') ];
130 return morphel;
131}
132
4c41c02c 133function color_inactive ( el ) {
134 var reading_id = $(el).parent().attr('id');
135 var reading_info = readingdata[reading_id];
136 // If the reading info has any non-disambiguated lexemes, color it yellow;
137 // otherwise color it green.
138 $(el).attr( {stroke:'green', fill:'#b3f36d'} );
bb3230b1 139 if( reading_info ) {
140 $.each( reading_info['lexemes'], function ( idx, lex ) {
141 if( !lex['is_disambiguated'] || lex['is_disambiguated'] == 0 ) {
142 $(el).attr( {stroke:'orange', fill:'#fee233'} );
143 }
144 });
145 }
4c41c02c 146}
147
997ebe92 148function relemmatize () {
149 // Send the reading for a new lemmatization and reopen the form.
a0a66634 150 $('#relemmatize_pending').show();
997ebe92 151 var reading_id = $('#reading_id').val()
152 ncpath = getReadingURL( reading_id );
153 form_values = {
154 'normal_form': $('#reading_normal_form').val(),
155 'relemmatize': 1 };
156 var jqjson = $.post( ncpath, form_values, function( data ) {
157 // Update the form with the return
158 if( 'id' in data ) {
159 // We got back a good answer. Stash it
160 readingdata[reading_id] = data;
161 // and regenerate the morphology form.
162 morphology_form( data['lexemes'] );
163 } else {
164 alert("Could not relemmatize as requested: " + data['error']);
165 }
a0a66634 166 $('#relemmatize_pending').hide();
997ebe92 167 });
168}
169
065c7cf2 170// Initialize the SVG once it exists
b28e606e 171function svgEnlargementLoaded() {
fc018906 172 //Give some visual evidence that we are working
173 $('#loading_overlay').show();
174 lo_height = $("#enlargement_container").outerHeight();
175 lo_width = $("#enlargement_container").outerWidth();
176 $("#loading_overlay").height( lo_height );
177 $("#loading_overlay").width( lo_width );
178 $("#loading_overlay").offset( $("#enlargement_container").offset() );
179 $("#loading_message").offset(
180 { 'top': lo_height / 2 - $("#loading_message").height() / 2,
181 'left': lo_width / 2 - $("#loading_message").width() / 2 });
30d0ba1e 182 if( editable ) {
183 // Show the update toggle button.
184 $('#update_workspace_button').data('locked', false);
185 $('#update_workspace_button').css('background-position', '0px 44px');
186 }
4c41c02c 187 var rdgpath = getTextURL( 'readings' );
188 $.getJSON( rdgpath, function( data ) {
189 readingdata = data;
190 $('#svgenlargement ellipse').each( function( i, el ) { color_inactive( el ) });
191 });
065c7cf2 192 $('#svgenlargement ellipse').parent().dblclick( node_dblclick_listener );
9529f69c 193 var graph_svg = $('#svgenlargement svg');
194 var svg_g = $('#svgenlargement svg g')[0];
76f05423 195 if (!svg_g) return;
9529f69c 196 svg_root = graph_svg.svg().svg('get').root();
76f05423 197
198 // Find the real root and ignore any text nodes
199 for (i = 0; i < svg_root.childNodes.length; ++i) {
200 if (svg_root.childNodes[i].nodeName != '#text') {
201 svg_root_element = svg_root.childNodes[i];
202 break;
203 }
204 }
205
30d0ba1e 206 //Set viewbox width and height to width and height of $('#svgenlargement svg').
207 //This is essential to make sure zooming and panning works properly.
9529f69c 208 svg_root.viewBox.baseVal.width = graph_svg.attr( 'width' );
209 svg_root.viewBox.baseVal.height = graph_svg.attr( 'height' );
210 //Now set scale and translate so svg height is about 150px and vertically centered in viewbox.
211 //This is just to create a nice starting enlargement.
212 var initial_svg_height = 250;
213 var scale = initial_svg_height/graph_svg.attr( 'height' );
214 var additional_translate = (graph_svg.attr( 'height' ) - initial_svg_height)/(2*scale);
215 var transform = svg_g.getAttribute('transform');
216 var translate = parseFloat( transform.match( /translate\([^\)]*\)/ )[0].split('(')[1].split(' ')[1].split(')')[0] );
217 translate += additional_translate;
218 var transform = 'rotate(0) scale(' + scale + ') translate(4 ' + translate + ')';
219 svg_g.setAttribute('transform', transform);
220 //used to calculate min and max zoom level:
4c41c02c 221 start_element_height = $('#__START__').children('ellipse')[0].getBBox().height;
fc018906 222 add_relations( function() { $('#loading_overlay').hide(); });
c1add777 223
224 //initialize marquee
225 marquee = new Marquee();
226
6afcd813 227}
228
fc018906 229function add_relations( callback_fn ) {
56e3972e 230 // Add the relationship types to the keymap list
56e3972e 231 $.each( relationship_types, function(index, typedef) {
671c04b1 232 li_elm = $('<li class="key">').css( "border-color",
233 relation_manager.relation_colors[index] ).text(typedef.name);
234 li_elm.append( $('<div>').attr('class', 'key_tip_container').append(
235 $('<div>').attr('class', 'key_tip').text(typedef.description) ) );
cfefd283 236 $('#keymaplist').append( li_elm );
56e3972e 237 });
238 // Now fetch the relationships themselves and add them to the graph
239 var rel_types = $.map( relationship_types, function(t) { return t.name });
240 // Save this list of names to the outer element data so that the relationship
241 // factory can access it
242 $('#keymap').data('relations', rel_types);
5f15640c 243 var textrelpath = getTextURL( 'relationships' );
56e3972e 244 $.getJSON( textrelpath, function(data) {
245 $.each(data, function( index, rel_info ) {
246 var type_index = $.inArray(rel_info.type, rel_types);
247 var source_found = get_ellipse( rel_info.source );
248 var target_found = get_ellipse( rel_info.target );
249 if( type_index != -1 && source_found.size() && target_found.size() ) {
250 var relation = relation_manager.create( rel_info.source, rel_info.target, type_index );
251 relation.data( 'type', rel_info.type );
252 relation.data( 'scope', rel_info.scope );
253 relation.data( 'note', rel_info.note );
30d0ba1e 254 if( editable ) {
255 var node_obj = get_node_obj(rel_info.source);
256 node_obj.set_draggable( false );
257 node_obj.ellipse.data( 'node_obj', null );
258 node_obj = get_node_obj(rel_info.target);
259 node_obj.set_draggable( false );
260 node_obj.ellipse.data( 'node_obj', null );
261 }
56e3972e 262 }
263 });
264 callback_fn.call();
265 });
b28e606e 266}
267
268function get_ellipse( node_id ) {
45ee3b96 269 return $( jq( node_id ) + ' ellipse');
b28e606e 270}
271
272function get_node_obj( node_id ) {
9529f69c 273 var node_ellipse = get_ellipse( node_id );
274 if( node_ellipse.data( 'node_obj' ) == null ) {
275 node_ellipse.data( 'node_obj', new node_obj(node_ellipse) );
276 };
277 return node_ellipse.data( 'node_obj' );
b28e606e 278}
279
b28e606e 280function node_obj(ellipse) {
281 this.ellipse = ellipse;
282 var self = this;
283
284 this.x = 0;
285 this.y = 0;
286 this.dx = 0;
287 this.dy = 0;
288 this.node_elements = node_elements_for(self.ellipse);
289
290 this.get_id = function() {
45ee3b96 291 return $(self.ellipse).parent().attr('id')
b28e606e 292 }
293
294 this.set_draggable = function( draggable ) {
30d0ba1e 295 if( draggable && editable ) {
05485bfd 296 $(self.ellipse).attr( {stroke:'black', fill:'#fff'} );
297 $(self.ellipse).parent().mousedown( this.mousedown_listener );
298 $(self.ellipse).parent().hover( this.enter_node, this.leave_node );
299 self.ellipse.siblings('text').attr('class', 'noselect draggable');
b28e606e 300 } else {
05485bfd 301 self.ellipse.siblings('text').attr('class', '');
4c41c02c 302 $(self.ellipse).parent().unbind( 'mouseenter' ).unbind( 'mouseleave' ).unbind( 'mousedown' );
303 color_inactive( self.ellipse );
b28e606e 304 }
305 }
306
307 this.mousedown_listener = function(evt) {
308 evt.stopPropagation();
309 self.x = evt.clientX;
310 self.y = evt.clientY;
311 $('body').mousemove( self.mousemove_listener );
312 $('body').mouseup( self.mouseup_listener );
05485bfd 313 $(self.ellipse).parent().unbind('mouseenter').unbind('mouseleave')
b28e606e 314 self.ellipse.attr( 'fill', '#ff66ff' );
315 first_node_g_element = $("#svgenlargement g .node" ).filter( ":first" );
316 if( first_node_g_element.attr('id') !== self.get_g().attr('id') ) { self.get_g().insertBefore( first_node_g_element ) };
317 }
318
319 this.mousemove_listener = function(evt) {
9529f69c 320 self.dx = (evt.clientX - self.x) / mouse_scale;
321 self.dy = (evt.clientY - self.y) / mouse_scale;
b28e606e 322 self.move_elements();
05485bfd 323 evt.returnValue = false;
324 evt.preventDefault();
325 return false;
b28e606e 326 }
327
328 this.mouseup_listener = function(evt) {
329 if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
45ee3b96 330 var source_node_id = $(self.ellipse).parent().attr('id');
05485bfd 331 var source_node_text = self.ellipse.siblings('text').text();
45ee3b96 332 var target_node_id = $('ellipse[fill="#ffccff"]').parent().attr('id');
05485bfd 333 var target_node_text = $('ellipse[fill="#ffccff"]').siblings("text").text();
b28e606e 334 $('#source_node_id').val( source_node_id );
05485bfd 335 $('#source_node_text').val( source_node_text );
b28e606e 336 $('#target_node_id').val( target_node_id );
05485bfd 337 $('#target_node_text').val( target_node_text );
b28e606e 338 $('#dialog-form').dialog( 'open' );
339 };
340 $('body').unbind('mousemove');
341 $('body').unbind('mouseup');
342 self.ellipse.attr( 'fill', '#fff' );
05485bfd 343 $(self.ellipse).parent().hover( self.enter_node, self.leave_node );
9529f69c 344 self.reset_elements();
b28e606e 345 }
f2fb96fc 346
b28e606e 347 this.cpos = function() {
348 return { x: self.ellipse.attr('cx'), y: self.ellipse.attr('cy') };
349 }
350
351 this.get_g = function() {
352 return self.ellipse.parent('g');
353 }
354
355 this.enter_node = function(evt) {
356 self.ellipse.attr( 'fill', '#ffccff' );
357 }
358
359 this.leave_node = function(evt) {
360 self.ellipse.attr( 'fill', '#fff' );
361 }
362
363 this.greyout_edges = function() {
364 $.each( self.node_elements, function(index, value) {
365 value.grey_out('.edge');
366 });
367 }
368
369 this.ungreyout_edges = function() {
370 $.each( self.node_elements, function(index, value) {
371 value.un_grey_out('.edge');
372 });
373 }
374
375 this.move_elements = function() {
376 $.each( self.node_elements, function(index, value) {
377 value.move(self.dx,self.dy);
378 });
379 }
380
381 this.reset_elements = function() {
382 $.each( self.node_elements, function(index, value) {
383 value.reset();
384 });
385 }
386
387 this.update_elements = function() {
388 self.node_elements = node_elements_for(self.ellipse);
389 }
390
a84ca4de 391 this.get_witnesses = function() {
392 return readingdata[self.get_id()].witnesses
393 }
394
b28e606e 395 self.set_draggable( true );
396}
397
398function svgshape( shape_element ) {
399 this.shape = shape_element;
400 this.move = function(dx,dy) {
401 this.shape.attr( "transform", "translate(" + dx + " " + dy + ")" );
402 }
403 this.reset = function() {
404 this.shape.attr( "transform", "translate( 0, 0 )" );
405 }
406 this.grey_out = function(filter) {
407 if( this.shape.parent(filter).size() != 0 ) {
408 this.shape.attr({'stroke':'#e5e5e5', 'fill':'#e5e5e5'});
409 }
410 }
411 this.un_grey_out = function(filter) {
412 if( this.shape.parent(filter).size() != 0 ) {
413 this.shape.attr({'stroke':'#000000', 'fill':'#000000'});
414 }
415 }
416}
417
418function svgpath( path_element, svg_element ) {
419 this.svg_element = svg_element;
420 this.path = path_element;
421 this.x = this.path.x;
422 this.y = this.path.y;
423 this.move = function(dx,dy) {
424 this.path.x = this.x + dx;
425 this.path.y = this.y + dy;
426 }
427 this.reset = function() {
428 this.path.x = this.x;
429 this.path.y = this.y;
430 }
431 this.grey_out = function(filter) {
432 if( this.svg_element.parent(filter).size() != 0 ) {
433 this.svg_element.attr('stroke', '#e5e5e5');
434 this.svg_element.siblings('text').attr('fill', '#e5e5e5');
05485bfd 435 this.svg_element.siblings('text').attr('class', 'noselect');
b28e606e 436 }
437 }
438 this.un_grey_out = function(filter) {
439 if( this.svg_element.parent(filter).size() != 0 ) {
440 this.svg_element.attr('stroke', '#000000');
441 this.svg_element.siblings('text').attr('fill', '#000000');
05485bfd 442 this.svg_element.siblings('text').attr('class', '');
b28e606e 443 }
444 }
445}
446
447function node_elements_for( ellipse ) {
448 node_elements = get_edge_elements_for( ellipse );
449 node_elements.push( new svgshape( ellipse.siblings('text') ) );
450 node_elements.push( new svgshape( ellipse ) );
451 return node_elements;
452}
453
454function get_edge_elements_for( ellipse ) {
455 edge_elements = new Array();
45ee3b96 456 node_id = ellipse.parent().attr('id');
b28e606e 457 edge_in_pattern = new RegExp( node_id + '$' );
458 edge_out_pattern = new RegExp( '^' + node_id );
459 $.each( $('#svgenlargement .edge,#svgenlargement .relation').children('title'), function(index) {
460 title = $(this).text();
461 if( edge_in_pattern.test(title) ) {
462 polygon = $(this).siblings('polygon');
463 if( polygon.size() > 0 ) {
464 edge_elements.push( new svgshape( polygon ) );
465 }
466 path_segments = $(this).siblings('path')[0].pathSegList;
467 edge_elements.push( new svgpath( path_segments.getItem(path_segments.numberOfItems - 1), $(this).siblings('path') ) );
468 }
469 if( edge_out_pattern.test(title) ) {
470 path_segments = $(this).siblings('path')[0].pathSegList;
471 edge_elements.push( new svgpath( path_segments.getItem(0), $(this).siblings('path') ) );
472 }
473 });
474 return edge_elements;
475}
476
477function relation_factory() {
478 var self = this;
479 this.color_memo = null;
480 //TODO: colors hard coded for now
481 this.temp_color = '#FFA14F';
482 this.relation_colors = [ "#5CCCCC", "#67E667", "#F9FE72", "#6B90D4", "#FF7673", "#E467B3", "#AA67D5", "#8370D8", "#FFC173" ];
483
484 this.create_temporary = function( source_node_id, target_node_id ) {
45ee3b96 485 var relation_id = get_relation_id( source_node_id, target_node_id );
486 var relation = $( jq( relation_id ) );
9529f69c 487 if( relation.size() == 0 ) {
b28e606e 488 draw_relation( source_node_id, target_node_id, self.temp_color );
489 } else {
490 self.color_memo = relation.children('path').attr( 'stroke' );
491 relation.children('path').attr( 'stroke', self.temp_color );
492 }
493 }
494 this.remove_temporary = function() {
495 var path_element = $('#svgenlargement .relation').children('path[stroke="' + self.temp_color + '"]');
496 if( self.color_memo != null ) {
497 path_element.attr( 'stroke', self.color_memo );
498 self.color_memo = null;
499 } else {
9529f69c 500 var temporary = path_element.parent('g').remove();
501 temporary.empty();
502 temporary = null;
b28e606e 503 }
504 }
505 this.create = function( source_node_id, target_node_id, color_index ) {
506 //TODO: Protect from (color_)index out of bound..
507 var relation_color = self.relation_colors[ color_index ];
9529f69c 508 var relation = draw_relation( source_node_id, target_node_id, relation_color );
509 get_node_obj( source_node_id ).update_elements();
510 get_node_obj( target_node_id ).update_elements();
511 return relation;
b28e606e 512 }
9529f69c 513 this.toggle_active = function( relation_id ) {
45ee3b96 514 var relation = $( jq( relation_id ) );
9529f69c 515 var relation_path = relation.children('path');
516 if( !relation.data( 'active' ) ) {
517 relation_path.css( {'cursor':'pointer'} );
518 relation_path.mouseenter( function(event) {
519 outerTimer = setTimeout( function() {
520 timer = setTimeout( function() {
45ee3b96 521 var related_nodes = get_related_nodes( relation_id );
522 var source_node_id = related_nodes[0];
523 var target_node_id = related_nodes[1];
9529f69c 524 $('#delete_source_node_id').val( source_node_id );
525 $('#delete_target_node_id').val( target_node_id );
526 self.showinfo(relation);
527 }, 500 )
528 }, 1000 );
529 });
530 relation_path.mouseleave( function(event) {
531 clearTimeout(outerTimer);
532 if( timer != null ) { clearTimeout(timer); }
533 });
534 relation.data( 'active', true );
535 } else {
536 relation_path.unbind( 'mouseenter' );
537 relation_path.unbind( 'mouseleave' );
538 relation_path.css( {'cursor':'inherit'} );
539 relation.data( 'active', false );
540 }
541 }
542 this.showinfo = function(relation) {
088a14af 543 $('#delete_relation_type').text( relation.data('type') );
544 $('#delete_relation_scope').text( relation.data('scope') );
69a19c91 545 if( relation.data( 'note' ) ) {
088a14af 546 $('#delete_relation_note').text('note: ' + relation.data( 'note' ) );
69a19c91 547 }
9529f69c 548 var points = relation.children('path').attr('d').slice(1).replace('C',' ').split(' ');
549 var xs = parseFloat( points[0].split(',')[0] );
550 var xe = parseFloat( points[1].split(',')[0] );
551 var ys = parseFloat( points[0].split(',')[1] );
552 var ye = parseFloat( points[3].split(',')[1] );
553 var p = svg_root.createSVGPoint();
554 p.x = xs + ((xe-xs)*1.1);
555 p.y = ye - ((ye-ys)/2);
76f05423 556 var ctm = svg_root_element.getScreenCTM();
9529f69c 557 var nx = p.matrixTransform(ctm).x;
558 var ny = p.matrixTransform(ctm).y;
559 var dialog_aria = $ ("div[aria-labelledby='ui-dialog-title-delete-form']");
560 $('#delete-form').dialog( 'open' );
561 dialog_aria.offset({ left: nx, top: ny });
562 }
563 this.remove = function( relation_id ) {
30d0ba1e 564 if( !editable ) {
565 return;
566 }
45ee3b96 567 var relation = $( jq( relation_id ) );
9529f69c 568 relation.remove();
b28e606e 569 }
570}
571
45ee3b96 572// Utility function to create/return the ID of a relation link between
573// a source and target.
574function get_relation_id( source_id, target_id ) {
575 var idlist = [ source_id, target_id ];
576 idlist.sort();
577 return 'relation-' + idlist[0] + '-...-' + idlist[1];
578}
579
580function get_related_nodes( relation_id ) {
581 var srctotarg = relation_id.substr( 9 );
582 return srctotarg.split('-...-');
583}
584
b28e606e 585function draw_relation( source_id, target_id, relation_color ) {
9529f69c 586 var source_ellipse = get_ellipse( source_id );
587 var target_ellipse = get_ellipse( target_id );
45ee3b96 588 var relation_id = get_relation_id( source_id, target_id );
9529f69c 589 var svg = $('#svgenlargement').children('svg').svg().svg('get');
590 var path = svg.createPath();
591 var sx = parseInt( source_ellipse.attr('cx') );
592 var rx = parseInt( source_ellipse.attr('rx') );
593 var sy = parseInt( source_ellipse.attr('cy') );
594 var ex = parseInt( target_ellipse.attr('cx') );
595 var ey = parseInt( target_ellipse.attr('cy') );
45ee3b96 596 var relation = svg.group( $("#svgenlargement svg g"),
597 { 'class':'relation', 'id':relation_id } );
9529f69c 598 svg.title( relation, source_id + '->' + target_id );
599 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 600 var relation_element = $('#svgenlargement .relation').filter( ':last' );
601 relation_element.insertBefore( $('#svgenlargement g g').filter(':first') );
9529f69c 602 return relation_element;
b28e606e 603}
604
c1add777 605function Marquee() {
606
607 var self = this;
608
609 this.enlargementOffset = $('#svgenlargement').offset();
610 this.svg_rect = $('#svgenlargement svg').svg('get');
611
612 this.show = function( event ) {
613 // TODO: uncolor possible selected
614 // TODO: unless SHIFT?
615 p = svg_root.createSVGPoint();
616 p.x = event.clientX - self.enlargementOffset.left;
617 p.y = event.clientY - self.enlargementOffset.top;
618 // NB: I think next line is officially needed, it's only
619 // coincidentally that viewport and svg scale 1 to 1 initially
620 // and therefor we don't need a transform?
621 // p.matrixTransform( svg_root_element.getCTM().inverse() );
622 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' } );
623 };
624
625 this.expand = function( event ) {
626 var rect = $('#marquee');
627 if( rect.length != 0 ) {
628 var pX = (event.clientX - self.enlargementOffset.left) - rect.attr("x");;
629 var pY = (event.clientY - self.enlargementOffset.top) - rect.attr("y");;
630 rect.attr("width", pX);
631 rect.attr("height", pY);
632 }
633 };
634
a84ca4de 635 this.select = function() {
c1add777 636 var rect = $('#marquee');
637 if( rect.length != 0 ) {
638 var left = $('#marquee').offset().left;
639 var top = $('#marquee').offset().top;
640 var right = left + parseInt( $('#marquee').attr( 'width' ) );
641 var bottom = top + parseInt( $('#marquee').attr( 'height' ) );
642 var tf = svg_root_element.getScreenCTM().inverse();
643 var p = svg_root.createSVGPoint();
644 p.x=left;
645 p.y=top;
646 var cx_min = p.matrixTransform(tf).x;
647 var cy_min = p.matrixTransform(tf).y;
648 p.x=right;
649 p.y=bottom;
650 var cx_max = p.matrixTransform(tf).x;
651 var cy_max = p.matrixTransform(tf).y;
a84ca4de 652 var witnesses = [];
c1add777 653 $('#svgenlargement ellipse').each( function( index ) {
654 var cx = parseInt( $(this).attr('cx') );
655 var cy = parseInt( $(this).attr('cy') );
656 if( cx > cx_min && cx < cx_max) {
657 if( cy > cy_min && cy < cy_max) {
658 // we actually heve no real 'selected' state for nodes, except coloring
659 $(this).attr( 'fill', '#ffccff' );
a84ca4de 660 var this_witnesses = $(this).data( 'node_obj' ).get_witnesses();
661 witnesses = arrayUnique( witnesses.concat( this_witnesses ) );
c1add777 662 }
663 }
664 });
a84ca4de 665 if( $('ellipse[fill="#ffccff"]').size() > 0 ) {
666 $.each( witnesses, function( index, value ) {
667 $('#multipleselect-form').append( '<input type="checkbox" name="witnesses" value="' + value + '">' + value + '<br>' );
668 });
669 $('#multipleselect-form').dialog( 'open' );
670 }
c1add777 671 self.svg_rect.remove( $('#marquee') );
672 }
673 };
674
675}
676
9529f69c 677
b28e606e 678$(document).ready(function () {
9529f69c 679
680 timer = null;
b28e606e 681 relation_manager = new relation_factory();
682
c1add777 683 $('#update_workspace_button').data('locked', false);
684
9529f69c 685 $('#enlargement').mousedown(function (event) {
b28e606e 686 $(this)
9529f69c 687 .data('down', true)
688 .data('x', event.clientX)
689 .data('y', event.clientY)
690 .data('scrollLeft', this.scrollLeft)
c1add777 691 stateTf = svg_root_element.getCTM().inverse();
692 var p = svg_root.createSVGPoint();
693 p.x = event.clientX;
694 p.y = event.clientY;
695 stateOrigin = p.matrixTransform(stateTf);
696
697 // Activate marquee if in interaction mode
698 if( $('#update_workspace_button').data('locked') == true ) { marquee.show( event ) };
699
700 event.returnValue = false;
701 event.preventDefault();
702 return false;
b28e606e 703 }).mouseup(function (event) {
a84ca4de 704 marquee.select();
c1add777 705 $(this).data('down', false);
b28e606e 706 }).mousemove(function (event) {
9529f69c 707 if( timer != null ) { clearTimeout(timer); }
708 if ( ($(this).data('down') == true) && ($('#update_workspace_button').data('locked') == false) ) {
709 var p = svg_root.createSVGPoint();
710 p.x = event.clientX;
711 p.y = event.clientY;
712 p = p.matrixTransform(stateTf);
713 var matrix = stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y);
714 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
76f05423 715 svg_root_element.setAttribute("transform", s);
b28e606e 716 }
c1add777 717 marquee.expand( event );
76f05423 718 event.returnValue = false;
719 event.preventDefault();
b28e606e 720 }).mousewheel(function (event, delta) {
9529f69c 721 event.returnValue = false;
722 event.preventDefault();
723 if ( $('#update_workspace_button').data('locked') == false ) {
76f05423 724 if (!delta || delta == null || delta == 0) delta = event.originalEvent.wheelDelta;
725 if (!delta || delta == null || delta == 0) delta = -1 * event.originalEvent.detail;
9529f69c 726 if( delta < -9 ) { delta = -9 };
727 var z = 1 + delta/10;
76f05423 728 z = delta > 0 ? 1 : -1;
729 var g = svg_root_element;
730 if (g && ((z<1 && (g.getScreenCTM().a * start_element_height) > 4.0) || (z>=1 && (g.getScreenCTM().a * start_element_height) < 100))) {
9529f69c 731 var root = svg_root;
732 var p = root.createSVGPoint();
76f05423 733 p.x = event.originalEvent.clientX;
734 p.y = event.originalEvent.clientY;
9529f69c 735 p = p.matrixTransform(g.getCTM().inverse());
76f05423 736 var scaleLevel = 1+(z/20);
737 var k = root.createSVGMatrix().translate(p.x, p.y).scale(scaleLevel).translate(-p.x, -p.y);
9529f69c 738 var matrix = g.getCTM().multiply(k);
739 var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
740 g.setAttribute("transform", s);
741 }
742 }
b28e606e 743 }).css({
744 'overflow' : 'hidden',
745 'cursor' : '-moz-grab'
746 });
747
c1add777 748
30d0ba1e 749 if( editable ) {
750 $( "#dialog-form" ).dialog({
751 autoOpen: false,
752 height: 270,
753 width: 290,
754 modal: true,
755 buttons: {
756 "Ok": function( evt ) {
757 $(evt.target).button("disable");
758 $('#status').empty();
759 form_values = $('#collapse_node_form').serialize();
760 ncpath = getTextURL( 'relationships' );
761 var jqjson = $.post( ncpath, form_values, function(data) {
762 $.each( data, function(item, source_target) {
763 var source_found = get_ellipse( source_target[0] );
764 var target_found = get_ellipse( source_target[1] );
765 var relation_found = $.inArray( source_target[2], $('#keymap').data('relations') );
766 if( source_found.size() && target_found.size() && relation_found > -1 ) {
767 var relation = relation_manager.create( source_target[0], source_target[1], relation_found );
eeea8fb6 768 relation.data( 'type', source_target[2] );
7b54e481 769 relation.data( 'scope', $('#scope :selected').text() );
770 relation.data( 'note', $('#note').val() );
45ee3b96 771 relation_manager.toggle_active( relation.attr('id') );
7b54e481 772 }
30d0ba1e 773 $(evt.target).button("enable");
774 });
775 $( "#dialog-form" ).dialog( "close" );
776 }, 'json' );
777 },
778 Cancel: function() {
779 $( this ).dialog( "close" );
780 }
781 },
782 create: function(event, ui) {
783 $(this).data( 'relation_drawn', false );
a166dca8 784 $('#rel_type').data( 'changed_after_open', false );
56e3972e 785 $.each( relationship_types, function(index, typedef) {
786 $('#rel_type').append( $('<option />').attr( "value", typedef.name ).text(typedef.name) );
787 });
788 $.each( relationship_scopes, function(index, value) {
789 $('#scope').append( $('<option />').attr( "value", value ).text(value) );
a166dca8 790 });
791 // Handler to clear the annotation field, the first time the relationship is
792 // changed after opening the form.
793 $('#rel_type').change( function () {
794 if( !$(this).data( 'changed_after_open' ) ) {
795 $('#note').val('');
796 }
797 $(this).data( 'changed_after_open', true );
798 });
30d0ba1e 799 },
800 open: function() {
801 relation_manager.create_temporary( $('#source_node_id').val(), $('#target_node_id').val() );
802 $(".ui-widget-overlay").css("background", "none");
803 $("#dialog_overlay").show();
804 $("#dialog_overlay").height( $("#enlargement_container").height() );
805 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
806 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
a166dca8 807 $('#rel_type').data( 'changed_after_open', false );
30d0ba1e 808 },
809 close: function() {
810 relation_manager.remove_temporary();
811 $( '#status' ).empty();
812 $("#dialog_overlay").hide();
813 }
814 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
21e6ebc7 815 if( ajaxSettings.url == getTextURL('relationships')
816 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
817 var error;
818 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
819 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
820 } else {
821 try {
822 var errobj = jQuery.parseJSON( jqXHR.responseText );
823 error = errobj.error + '</br>The relationship cannot be made.</p>';
824 } catch(e) {
825 error = jqXHR.responseText;
826 }
827 }
828 $('#status').append( '<p class="error">Error: ' + error );
829 }
830 $(event.target).parent().find('.ui-button').button("enable");
30d0ba1e 831 } );
832 }
b28e606e 833
088a14af 834 var deletion_buttonset = {
835 cancel: function() { $( this ).dialog( "close" ); },
836 global: function () { delete_relation( true ); },
837 delete: function() { delete_relation( false ); }
838 };
a84ca4de 839
9529f69c 840 $( "#delete-form" ).dialog({
841 autoOpen: false,
69a19c91 842 height: 135,
088a14af 843 width: 250,
9529f69c 844 modal: false,
9529f69c 845 create: function(event, ui) {
30d0ba1e 846 // TODO What is this logic doing?
a84ca4de 847 // This scales the buttons in the dialog and makes it look proper
848 // Not sure how essential it is, does anything break if it's not here?
9529f69c 849 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
850 buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
a84ca4de 851 // A: This makes sure that the pop up delete relation dialogue for a hovered over
852 // relation auto closes if the user doesn't engage (mouseover) with it.
9529f69c 853 var dialog_aria = $("div[aria-labelledby='ui-dialog-title-delete-form']");
854 dialog_aria.mouseenter( function() {
855 if( mouseWait != null ) { clearTimeout(mouseWait) };
856 })
857 dialog_aria.mouseleave( function() {
858 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
859 })
860 },
861 open: function() {
088a14af 862 if( !editable ) {
863 $( this ).dialog( "option", "buttons",
864 [{ text: "OK", click: deletion_buttonset['cancel'] }] );
865 } else if( $('#delete_relation_scope').text() === 'local' ) {
866 $( this ).dialog( "option", "width", 160 );
867 $( this ).dialog( "option", "buttons",
868 [{ text: "Delete", click: deletion_buttonset['delete'] },
869 { text: "Cancel", click: deletion_buttonset['cancel'] }] );
870 } else {
871 $( this ).dialog( "option", "width", 200 );
872 $( this ).dialog( "option", "buttons",
873 [{ text: "Delete", click: deletion_buttonset['delete'] },
874 { text: "Delete all", click: deletion_buttonset['global'] },
875 { text: "Cancel", click: deletion_buttonset['cancel'] }] );
876 }
877
9529f69c 878 mouseWait = setTimeout( function() { $("#delete-form").dialog( "close" ) }, 2000 );
879 },
088a14af 880 close: function() {}
9529f69c 881 });
882
a84ca4de 883 var multipleselect_buttonset = {
884 cancel: function() { $( this ).dialog( "close" ); },
885 button1: function () { },
886 button2: function() { }
887 };
888
889 $( "#multipleselect-form" ).dialog({
890 autoOpen: false,
891 height: 150,
892 width: 250,
893 modal: true,
894 create: function(event, ui) {
895 var buttonset = $(this).parent().find( '.ui-dialog-buttonset' ).css( 'width', '100%' );
896 buttonset.find( "button:contains('Cancel')" ).css( 'float', 'right' );
897 },
898 open: function() {
899 $( this ).dialog( "option", "width", 200 );
900 $( this ).dialog( "option", "buttons",
901 [{ text: "Button_1", click: multipleselect_buttonset['button1'] },
902 { text: "Button_2", click: multipleselect_buttonset['button2'] },
903 { text: "Cancel", click: multipleselect_buttonset['cancel'] }] );
904 },
905 close: function() {}
906 });
907
088a14af 908 // Helpers for relationship deletion
909
910 function delete_relation( scopewide ) {
911 form_values = $('#delete_relation_form').serialize();
912 if( scopewide ) {
913 form_values += "&scopewide=true";
914 }
915 ncpath = getTextURL( 'relationships' );
916 var jqjson = $.ajax({ url: ncpath, data: form_values, success: function(data) {
917 $.each( data, function(item, source_target) {
918 relation_manager.remove( get_relation_id( source_target[0], source_target[1] ) );
919 });
920 $( "#delete-form" ).dialog( "close" );
921 }, dataType: 'json', type: 'DELETE' });
922 }
923
924 function toggle_relation_active( node_id ) {
925 $('#svgenlargement .relation').find( "title:contains('" + node_id + "')" ).each( function(index) {
926 matchid = new RegExp( "^" + node_id );
927 if( $(this).text().match( matchid ) != null ) {
928 var relation_id = $(this).parent().attr('id');
929 relation_manager.toggle_active( relation_id );
930 };
931 });
932 }
933
487674b9 934 // function for reading form dialog should go here;
935 // just hide the element for now if we don't have morphology
936 if( can_morphologize ) {
5539cba3 937 if( editable ) {
938 $('#reading_decollate_witnesses').multiselect();
939 } else {
940 $('#decollation').hide();
941 }
487674b9 942 $('#reading-form').dialog({
943 autoOpen: false,
944 // height: 400,
945 width: 450,
946 modal: true,
947 buttons: {
948 Cancel: function() {
949 $( this ).dialog( "close" );
950 },
951 Update: function( evt ) {
952 // Disable the button
953 $(evt.target).button("disable");
954 $('#reading_status').empty();
955 var reading_id = $('#reading_id').val()
956 form_values = {
957 'id' : reading_id,
958 'is_nonsense': $('#reading_is_nonsense').is(':checked'),
959 'grammar_invalid': $('#reading_grammar_invalid').is(':checked'),
960 'normal_form': $('#reading_normal_form').val() };
961 // Add the morphology values
962 $('.reading_morphology').each( function() {
963 if( $(this).val() != '(Click to select)' ) {
964 var rmid = $(this).attr('id');
965 rmid = rmid.substring(8);
966 form_values[rmid] = $(this).val();
967 }
45ee3b96 968 });
487674b9 969 // Make the JSON call
970 ncpath = getReadingURL( reading_id );
971 var reading_element = readingdata[reading_id];
972 // $(':button :contains("Update")').attr("disabled", true);
973 var jqjson = $.post( ncpath, form_values, function(data) {
974 $.each( data, function(key, value) {
975 reading_element[key] = value;
976 });
977 if( $('#update_workspace_button').data('locked') == false ) {
978 color_inactive( get_ellipse( reading_id ) );
979 }
980 $(evt.target).button("enable");
981 $( "#reading-form" ).dialog( "close" );
982 });
983 // Re-color the node if necessary
984 return false;
985 }
986 },
987 create: function() {
30d0ba1e 988 if( !editable ) {
989 // Get rid of the disallowed editing UI bits
990 $( this ).dialog( "option", "buttons",
991 [{ text: "OK", click: function() { $( this ).dialog( "close" ); }}] );
992 $('#reading_relemmatize').hide();
993 }
487674b9 994 },
995 open: function() {
996 $(".ui-widget-overlay").css("background", "none");
5539cba3 997 $('#reading_decollate_witnesses').multiselect("refresh");
998 $('#reading_decollate_witnesses').multiselect("uncheckAll");
487674b9 999 $("#dialog_overlay").show();
1000 $('#reading_status').empty();
1001 $("#dialog_overlay").height( $("#enlargement_container").height() );
1002 $("#dialog_overlay").width( $("#enlargement_container").innerWidth() );
1003 $("#dialog_overlay").offset( $("#enlargement_container").offset() );
1004 $("#reading-form").parent().find('.ui-button').button("enable");
1005 },
1006 close: function() {
1007 $("#dialog_overlay").hide();
1008 }
1009 }).ajaxError( function(event, jqXHR, ajaxSettings, thrownError) {
21e6ebc7 1010 if( ajaxSettings.url.lastIndexOf( getReadingURL('') ) > -1
487674b9 1011 && ajaxSettings.type == 'POST' && jqXHR.status == 403 ) {
21e6ebc7 1012 var error;
1013 if( jqXHR.responseText.indexOf('do not have permission to modify') > -1 ) {
1014 error = 'You are not authorized to modify this tradition. (Try logging in again?)';
1015 } else {
1016 try {
1017 var errobj = jQuery.parseJSON( jqXHR.responseText );
1018 error = errobj.error + '</br>The relationship cannot be made.</p>';
1019 } catch(e) {
1020 error = jqXHR.responseText;
1021 }
1022 }
1023 $('#status').append( '<p class="error">Error: ' + error );
1024 }
1025 $(event.target).parent().find('.ui-button').button("enable");
487674b9 1026 });
1027 } else {
1028 $('#reading-form').hide();
45ee3b96 1029 }
4c41c02c 1030
76f05423 1031
b28e606e 1032 $('#update_workspace_button').click( function() {
30d0ba1e 1033 if( !editable ) {
1034 return;
1035 }
b28e606e 1036 var svg_enlargement = $('#svgenlargement').svg().svg('get').root();
76f05423 1037 mouse_scale = svg_root_element.getScreenCTM().a;
9529f69c 1038 if( $(this).data('locked') == true ) {
1039 $('#svgenlargement ellipse' ).each( function( index ) {
1040 if( $(this).data( 'node_obj' ) != null ) {
1041 $(this).data( 'node_obj' ).ungreyout_edges();
1042 $(this).data( 'node_obj' ).set_draggable( false );
1043 var node_id = $(this).data( 'node_obj' ).get_id();
1044 toggle_relation_active( node_id );
1045 $(this).data( 'node_obj', null );
1046 }
b28e606e 1047 })
b28e606e 1048 $(this).data('locked', false);
9529f69c 1049 $(this).css('background-position', '0px 44px');
b28e606e 1050 } else {
9529f69c 1051 var left = $('#enlargement').offset().left;
1052 var right = left + $('#enlargement').width();
76f05423 1053 var tf = svg_root_element.getScreenCTM().inverse();
9529f69c 1054 var p = svg_root.createSVGPoint();
1055 p.x=left;
1056 p.y=100;
1057 var cx_min = p.matrixTransform(tf).x;
1058 p.x=right;
1059 var cx_max = p.matrixTransform(tf).x;
1060 $('#svgenlargement ellipse').each( function( index ) {
1061 var cx = parseInt( $(this).attr('cx') );
1062 if( cx > cx_min && cx < cx_max) {
1063 if( $(this).data( 'node_obj' ) == null ) {
1064 $(this).data( 'node_obj', new node_obj( $(this) ) );
1065 } else {
1066 $(this).data( 'node_obj' ).set_draggable( true );
1067 }
1068 $(this).data( 'node_obj' ).greyout_edges();
1069 var node_id = $(this).data( 'node_obj' ).get_id();
1070 toggle_relation_active( node_id );
b28e606e 1071 }
9529f69c 1072 });
1073 $(this).css('background-position', '0px 0px');
b28e606e 1074 $(this).data('locked', true );
b28e606e 1075 }
1076 });
30d0ba1e 1077
1078 if( !editable ) {
1079 // Hide the unused elements
1080 $('#dialog-form').hide();
1081 $('#update_workspace_button').hide();
1082 }
1083
b28e606e 1084
e847b186 1085 $('.helptag').popupWindow({
1086 height:500,
1087 width:800,
1088 top:50,
1089 left:50,
1090 scrollbars:1
1091 });
1092
76f05423 1093 expandFillPageClients();
1094 $(window).resize(function() {
1095 expandFillPageClients();
1096 });
1097
9529f69c 1098});
b28e606e 1099
1100
76f05423 1101function expandFillPageClients() {
1102 $('.fillPage').each(function () {
1103 $(this).height($(window).height() - $(this).offset().top - MARGIN);
1104 });
1105}
1106
1107function loadSVG(svgData) {
1108 var svgElement = $('#svgenlargement');
1109
1110 $(svgElement).svg('destroy');
1111
1112 $(svgElement).svg({
1113 loadURL: svgData,
1114 onLoad : svgEnlargementLoaded
1115 });
1116}
1117
1118
c1add777 1119
76f05423 1120/* OS Gadget stuff
1121
1122function svg_select_callback(topic, data, subscriberData) {
1123 svgData = data;
1124 loadSVG(svgData);
1125}
1126
1127function loaded() {
1128 var prefs = new gadgets.Prefs();
1129 var preferredHeight = parseInt(prefs.getString('height'));
1130 if (gadgets.util.hasFeature('dynamic-height')) gadgets.window.adjustHeight(preferredHeight);
1131 expandFillPageClients();
1132}
1133
1134if (gadgets.util.hasFeature('pubsub-2')) {
1135 gadgets.HubSettings.onConnect = function(hum, suc, err) {
1136 subId = gadgets.Hub.subscribe("interedition.svg.selected", svg_select_callback);
1137 loaded();
1138 };
1139}
1140else gadgets.util.registerOnLoadHandler(loaded);
1141*/